首页 > 代码库 > 【LeetCode】Construct Binary Tree from Preorder and Inorder Traversal 解题报告

【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.

【解析】

题意:根据二叉树先序遍历和中序遍历的结果,构造二叉树。跟 根据中序遍历和后序遍历结果构造二叉树 类似。

先序遍历:root - left - right,中序遍历:left - root - right。

不同的是,先序遍历的第一个元素就是根节点。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    int[] preorder;
    int[] inorder;
    
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder.length < 1 || inorder.length < 1) return null;
        this.preorder = preorder;
        this.inorder = inorder;
        return getRoot(0, inorder.length - 1, 0);
    }
    
    // sub-tree range form begin to end in inorder[]
    // rootpos refer the root postion in preorder[]
    public TreeNode getRoot(int begin, int end, int rootpos) {
        if (begin > end) return null;
        TreeNode root = new TreeNode(preorder[rootpos]);
        int i;
        for (i = begin; i <= end; i++) {
            if (inorder[i] == preorder[rootpos]) break;
        }
        // left part length: i - begin, right part length: end - i
        root.left = getRoot(begin, i - 1, rootpos + 1);
        root.right = getRoot(i + 1, end, rootpos + 1 + (i - begin));
        return root;
    }
}


【LeetCode】Construct Binary Tree from Preorder and Inorder Traversal 解题报告