105. Construct Binary Tree from Preorder and Inorder Traversal

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;
    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值