您的位置:首页 > 其它

LeetCode: Construct Binary Tree from Inorder and Postorder Traversal 解题报告

2015-01-03 16:36 417 查看

Construct Binary Tree from Inorder and Postorder Traversal

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

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

Hide Tags

Tree Array Depth-first Search

SOLUTION 1:

使用递归的思想,先找到根节点(它就是post order最后一个),然后再在inorder中找到它,以确定左子树的node个数。
然后分别确定左子树右子树的左右边界
例子:
{4, 5, 2, 7, 8, 1, 3}这树的
inorder: 7 5 8 | 4 | 1 2 3
post: 7 8 5 | 1 3 2 | 4
以上我们可以看到左右子树的划分关系。

/**
* 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[] inorder, int[] postorder) {
if (inorder == null || postorder == null) {
return null;
}

return dfs(inorder, postorder, 0, inorder.length - 1, 0, postorder.length - 1);
}

public TreeNode dfs(int[] inorder, int[] postorder, int inL, int inR, int postL, int postR) {
if (inL > inR) {
return null;
}

// create the root node.
TreeNode root = new TreeNode(postorder[postR]);

// find the position of the root node in the inorder traversal.
int pos = 0;
for (; pos <= inR; pos++) {
if (inorder[pos] == postorder[postR]) {
break;
}
}

int leftNum = pos - inL;

root.left = dfs(inorder, postorder, inL, pos - 1, postL, postL + leftNum - 1);
root.right = dfs(inorder, postorder, pos + 1, inR, postL + leftNum, postR - 1);

return root;
}
}


View Code
代码: https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/tree/BuildTree2.java
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐