您的位置:首页 > 其它

Construct Binary Tree from Preorder and Inorder Traversal

2013-11-16 06:37 190 查看
Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

本来想先对inorder array做预处理存上val对应的index,结果发现 val可能有duplicates。

/**duplicates
* Definition for binary tree
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
return preorder_inorder(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
}
public TreeNode preorder_inorder(int[] pre, int ps, int pe, int[] in, int is, int ie){
if(ps > pe || is > ie) return null;
TreeNode root = new TreeNode(pre[ps]);
int ind = 0;
for(int i = is; i <= ie; i++)
if(in[i] == root.val){
ind = i;
break;
}
int len = ind - is;
root.left = preorder_inorder(pre, ps + 1, ps + len, in, is, ind - 1);
root.right = preorder_inorder(pre, ps + 1 + len, pe, in, ind + 1, ie);
return root;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐