Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
解题思路:给出前序和中序遍历,重建二叉树,根据前序找到跟节点,然后将中序分为两部分,分别在两部分中递归找到左右孩子节点。非递归用栈保存节点,遍历前序,每次判断中序位置是否为切分点。
一刷ac,非递归需要再刷
递归方法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder == null || inorder == null) return null;
return construct(preorder, 0, inorder, 0, inorder.length-1);
}
public static TreeNode construct(int[] preorder, int pre_start, int[] inorder, int in_start, int in_end){
if(pre_start >= preorder.length || in_start > in_end) return null;
TreeNode root = new TreeNode(preorder[pre_start]);
for(int i = in_start; i <= in_end; i++){
if(preorder[pre_start] == inorder[i]){
root.left = construct(preorder, pre_start+1, inorder, in_start, i-1);
root.right = construct(preorder, pre_start+i-in_start+1, inorder, i+1, in_end);
}
}
return root;
}
}
非递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder == null || inorder == null || preorder.length == 0 || inorder.length == 0) return null;
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode root = new TreeNode(preorder[0]);
stack.push(root);
int index = 0;
for(int i = 1; i < preorder.length; i++){
TreeNode node = stack.peek();
if(node.val != inorder[index]){
TreeNode tmp = new TreeNode(preorder[i]);
node.left = tmp;
stack.push(tmp);
}else{
while(!stack.isEmpty() && stack.peek().val == inorder[index]){
node = stack.pop();
index++;
}
TreeNode tmp = new TreeNode(preorder[i]);
node.right = tmp;
stack.push(tmp);
}
}
return root;
}
}