Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

难度:Medium

题目: 给定二叉树的前序和中序遍历,构造二叉树,注意:二叉树结点值不重复。

思路:分治,

  1. 在前序中找出根结点r,
  2. 再在中序中找出r的位置,以该结点一分为二,继续执行1

Runtime: 8 ms, faster than 57.64% of Java online submissions for Construct Binary Tree from Preorder and Inorder Traversal.
Memory Usage: 37.5 MB, less than 49.23% of Java online submissions for Construct Binary Tree from Preorder and Inorder Traversal.

/**
 * 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 (null == preorder || preorder.length < 1) {
            return null;
        }
        
        return buildTree(preorder, 0, inorder, 0, inorder.length - 1);
    }
    
    private TreeNode buildTree(int[] preorder, int idx, int[] inorder, int s, int e) {
        if (s > e) {
            return null;
        }
        TreeNode root = new TreeNode(preorder[idx]);
        int rIdx = s;
        for (; rIdx <= e; rIdx++) {
            if (inorder[rIdx] == preorder[idx]) {
                break;
            }
        }
        root.left = buildTree(preorder, idx + 1, inorder, s, rIdx - 1);
        root.right = buildTree(preorder, idx + rIdx - s + 1, inorder, rIdx + 1, e);
        
        return root;
    }
}

linm
1 声望4 粉丝

〜〜〜学习始于模仿,成长得于总结〜〜〜