Construct Binary Tree from Preorder and Inorder Traversal

Posted beiyeqingteng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

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


 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public TreeNode buildTree(int[] preorder, int[] inorder) {
12         if (preorder == null || inorder == null || preorder.length == 0 || inorder.length != preorder.length) return null;
13         return buildTree(inorder, 0, preorder, 0, inorder.length);
14     }
15     
16     public TreeNode buildTree(int[] inorder, int inStart, int[] preorder, int preStart, int length) {
17         if (length == 0) return null;
18         TreeNode root = new TreeNode(preorder[preStart]);
19         int index = findIndex(inorder, root.val);
20         root.left = buildTree(inorder, inStart, preorder, preStart + 1, index - inStart);
21         root.right = buildTree(inorder, index + 1, preorder, preStart + (index - inStart) + 1, length - (index - inStart) - 1);
22         return root;    
23     }
24     
25     public int findIndex(int[] inorder, int val) {
26         for (int i = 0; i < inorder.length; i++) {
27             if (inorder[i] == val) {
28                 return i;
29             }
30         }
31         return -1;
32     }
33 }

 

以上是关于Construct Binary Tree from Preorder and Inorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章

606. Construct String from Binary Tree

606. Construct String from Binary Tree

LeetCode Construct String from Binary Tree

Construct String From Binary Tree

E. Construct the Binary Tree。。。

1008. Construct Binary Search Tree from Preorder Traversal