106. 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.
解法
后序遍历的最后一个元素为根节点,在中序遍历中找到该根节点,中序遍历中,该元素的左边为左子树,右边为右子树。
/**
* 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 || inorder.length == 0) && (postorder == null || postorder.length == 0)) {
return null;
}
return helper(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
}
private TreeNode helper(int[] inorder, int inStart, int inEnd, int[] postorder, int postStart, int postEnd) {
if (inStart > inEnd || postStart > postEnd) {
return null;
}
TreeNode root = new TreeNode(postorder[postEnd]);
int inIndex = 0;
for (int i = inStart; i <= inEnd; i++) {
if (inorder[i] == root.val) {
inIndex = i;
break;
}
}
root.left = helper(inorder, inStart, inIndex - 1, postorder, postStart, postStart + inIndex - inStart - 1);
root.right = helper(inorder, inIndex + 1, inEnd, postorder, postStart + inIndex - inStart, postEnd - 1);
return root;
}
}

本文介绍了一种通过中序和后序遍历来构建二叉树的方法。解析了算法思路:利用后序遍历的最后一个元素作为根节点,在中序遍历中定位该节点,以此划分左右子树,并递归构建。
2031

被折叠的 条评论
为什么被折叠?



