您的位置:首页 > 其它

106. Construct Binary Tree from Inorder and Postorder Traversal

2015-04-18 13:46 411 查看
题目:

Given inorder and postorder traversal of a tree, construct the binary tree.

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

链接: http://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/

题解:

和上一题一样,不过这次的root是从post order的后面来找。

Time Complexity - O(n), Space Complexity - O(n)。

/**
* 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 == null || postorder == null || inorder.length != postorder.length || inorder.length == 0)
return null;
return buildTree(postorder, 0, postorder.length - 1, inorder, 0, inorder.length - 1);
}

private TreeNode buildTree(int[] postorder, int postLo, int postHi, int[] inorder, int inLo, int inHi) {
if(postLo > postHi || inLo > inHi)
return null;
TreeNode root = new TreeNode(postorder[postHi]);
int rootIndex = 0;
for(int i = inLo; i <= inHi; i++) {
if(inorder[i] == root.val) {
rootIndex = i;
break;
}
}
int leftTreeLen = rootIndex - inLo;
root.left = buildTree(postorder, postLo, postLo + leftTreeLen - 1, inorder, inLo, rootIndex - 1);
root.right = buildTree(postorder, postLo + leftTreeLen, postHi - 1, inorder, rootIndex + 1, inHi);
return root;
}
}


测试:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: