码迷,mamicode.com
首页 > 其他好文 > 详细

Construct Binary Tree from Preorder and Inorder Traversal

时间:2019-03-04 09:23:18      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:pre   round   span   star   nbsp   ==   hat   OWIN   may   

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

标签:pre   round   span   star   nbsp   ==   hat   OWIN   may   

原文地址:https://www.cnblogs.com/beiyeqingteng/p/10468683.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!