欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

105. Construct Binary Tree from Preorder and Inorder Traversal

程序员文章站 2022-03-03 10:20:59
...

105. Construct Binary Tree from Preorder and Inorder Traversal

Medium

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

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private static int idx = 0;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (null == preorder || preorder.length < 1) {
            return null;
        }
        
        int[] idx = {0};
        
        return buildTree(preorder, idx, inorder, 0, inorder.length - 1);
    }
    
    private TreeNode buildTree(int[] preorder, int[] idx, int[] inorder, int s, int e) {
        int rIdx = s;
        for (int i = s; i <= e; i++) {
            if (preorder[idx[0]] == inorder[i]) {
                rIdx = i;
                break;
            }
        }

        TreeNode root = new TreeNode(preorder[idx[0]]);
        if (rIdx - s >= 1) {
            idx[0] += 1;
            root.left = buildTree(preorder, idx, inorder, s, rIdx - 1);
        }
        
        if (e - rIdx >= 1) {
            idx[0] += 1;
            root.right = buildTree(preorder, idx, inorder, rIdx + 1, e);
        }
        
        return root;   
    }
}