您的位置:首页 > 其它

Construct Binary Tree from Inorder and Postorder Traversal

2015-07-07 14:14 288 查看
/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if (inorder.length != postorder.length) {
return null;
}
return myBuildTree(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
}
private TreeNode myBuildTree(int[] inorder, int inBeg, int inEnd, int[] postorder, int postBeg, int postEnd) {
if (inBeg > inEnd) {
return null;
}
TreeNode root = new TreeNode(postorder[postEnd]);
int location = findLocation(inorder, inBeg, inEnd, postorder[postEnd]);
root.left = myBuildTree(inorder, inBeg, location - 1, postorder, postBeg, postBeg + location - inBeg - 1);
root.right = myBuildTree(inorder, location + 1, inEnd, postorder, postEnd + location - inEnd, postEnd - 1);
return root;
}
private int findLocation(int[] inorder, int begin, int end, int value) {
for (int i = begin; i <= end; i++) {
if (inorder[i] == value) {
return i;
}
}
return -1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Array DFS Tree