标签:init 中序遍历 限制 index 节点 else ack public dex
输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
限制:
0 <= 节点个数 <= 5000
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length==0) return null;
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<inorder.length;i++){
map.put(inorder[i],i);
}
TreeNode root=build(preorder,0,preorder.length-1,inorder,0,inorder.length-1,map);
return root;
}
public TreeNode build(int[] preorder,int ps,int pe,int[] inorder,int is,int ie,Map<Integer,Integer> map){
if(ps>pe){
return null;
}
int rootval=preorder[ps];
TreeNode root=new TreeNode(rootval);
if(ps==pe){
return root;
}else{
int index=map.get(rootval);
int lefts=index-is;
int rights=ie-index;
root.left=build(preorder,ps+1,ps+lefts,inorder,is,index-1,map);
root.right=build(preorder,ps+lefts+1,pe,inorder,index+1,ie,map);
return root;
}
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length==0) return null;
TreeNode root=new TreeNode(preorder[0]);
Stack<TreeNode> stack=new Stack<>();
int len=preorder.length;
stack.push(root);
int index=0;
for(int i=1;i<len;i++){
int pre=preorder[i];
TreeNode node=stack.peek();
if(node.val!=inorder[index]){
node.left=new TreeNode(pre);
stack.push(node.left);
}else{
while(!stack.isEmpty()&&stack.peek().val==inorder[index]){
node=stack.pop();
index++;
}
node.right=new TreeNode(pre);
stack.push(node.right);
}
}
return root;
}
}
标签:init 中序遍历 限制 index 节点 else ack public dex
原文地址:https://www.cnblogs.com/xyz-1024/p/13956416.html