LeetCode题解: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.

题意:给定一棵树的先序遍历和中序遍历,还原该树

解决思路:在中序遍历中,每一个根节点的左方为其左子树,右方为右子树;而在先序遍历中第一个节点为根节点。利用这两点可以解决

代码:

public class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return helper(0, 0, inorder.length - 1, preorder, inorder);
    }

    private TreeNode helper(int preStart, int inStart, int inEnd, int[] preorder, int[] inorder){
        if(preStart > preorder.length - 1 || inStart > inEnd){
            return null;
        }


        int index = 0;
        TreeNode root = new TreeNode(preorder[preStart]);
        for(int i = inStart; i <= inEnd; i++){
            if(inorder[i] == root.val){
                index = i;
                break;
            }
        }

        root.left = helper(preStart + 1, inStart, index - 1, preorder, inorder);
        root.right = helper(preStart + index - inStart + 1, index + 1, inEnd, preorder, inorder);

        return root;
    }
}

你可能感兴趣的:(LeetCode题解:Construct Binary Tree from Preorder and Inorder Traversal)