LeetCode刷题实战105:从前序与中序遍历序列构造二叉树
共 1291字,需浏览 3分钟
·
2020-11-26 21:59
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 从前序与中序遍历序列构造二叉树,我们先来看题面:
https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
题意
解题
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length>0) {
TreeNode root =new TreeNode(preorder[0]);
Listorder=new ArrayList ();
for(int i=0;iorder.add(inorder[i]);
}
getTree(preorder,0,order,root);
return root;
} else {
return null;
}
}
public void getTree(int[]preorder ,int number,Listorder,TreeNode root ) {
if(order.size()==1) {
return ;
}
int ordernum=order.indexOf(preorder[number]);
if(ordernum>0) {
ListleftOrder=new ArrayList (order.subList(0, ordernum));
for(int i=number+1;i{
if(leftOrder.contains(preorder[i])) {
root.left=new TreeNode(preorder[i]);
getTree(preorder,i,leftOrder,root.left);
break;
}
}
}
if(ordernum-1)
{
ListrightOrder=new ArrayList (order.subList(ordernum+1, order.size()));
for(int j=number+1;jif(rightOrder.contains(preorder[j])) {
root.right=new TreeNode(preorder[j]);
getTree(preorder,j,rightOrder,root.right);
break;
}
}
}
}
}
上期推文: