首页 > 其他 > 详细

[leetcode]Construct Binary Tree from Preorder and Inorder Traversal

时间:2014-07-31 23:26:10      阅读:384      评论:0      收藏:0      [点我收藏+]

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.

算法思路:

根据前序序列和中序序列构建树。递归,没难度。

 1 public class Solution {
 2     public TreeNode buildTree(int[] preorder, int[] inorder) {
 3         if(preorder == null || inorder == null || preorder.length != inorder.length || preorder.length == 0) return null;
 4         int val = preorder[0],length = inorder.length;
 5         int mid = 0;
 6         for(int i = 0; i < length; i++){
 7             if(inorder[i] == val){
 8                 mid = i;
 9                 break;
10             }
11         }
12         int[] leftPre = Arrays.copyOfRange(preorder, 1, mid + 1);
13         int[] leftIn = Arrays.copyOfRange(inorder, 0, mid);
14         int[] rightPre = Arrays.copyOfRange(preorder, mid + 1, length);
15         int[] rightIn = Arrays.copyOfRange(inorder, mid + 1, length);
16         TreeNode root = new TreeNode(val);
17         root.left = buildTree(leftPre, leftIn);
18         root.right = buildTree(rightPre,rightIn);
19         return root;
20     }
21 }

 

[leetcode]Construct Binary Tree from Preorder and Inorder Traversal,布布扣,bubuko.com

[leetcode]Construct Binary Tree from Preorder and Inorder Traversal

原文:http://www.cnblogs.com/huntfor/p/3883517.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!