Construct Binary Tree from Inorder and Postorder Traversal (M)
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
题意
给定一棵二叉树的后序序列和中序序列,要求重建这棵二叉树。
思路
由二叉树的性质可知,后序序列的最后一个元素是当前二叉树的根节点,根节点将中序序列分为左子树和右子树。后序序列的最后一个元素即为整棵二叉树的根节点,在中序序列中找到该元素,则中序中该元素左侧为左子树,右侧为右子树,依照左右子树个数又可将后序序列剩余元素进行划分,接着只要对左子树和右子树进行递归操作即可。
代码实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
// 为了省去在中序序列中迭代查找元素的时间, 直接用HashMap将整个inorder存进去
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
map.put(inorder[i], i);
}
return buildTree(map, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
}
private TreeNode buildTree(Map<Integer, Integer> map, int inI, int inJ, int[] postorder, int postI, int postJ) {
// 递归边界
if (postI > postJ) {
return null;
}
if (postI == postJ) {
return new TreeNode(postorder[postJ]);
}
// 在中序序列中找到后序序列的最后一个元素,并求出左子树的长度
int len = map.get(postorder[postJ]) - inI;
TreeNode root = new TreeNode(postorder[postJ]);
// 划分区域后递归处理左右子树
root.left = buildTree(map, inI, inI + len - 1, postorder, postI, postI + len - 1);
root.right = buildTree(map, inI + len + 1, inJ, postorder, postI + len, postJ - 1);
return root;
}
}
本文介绍了一种算法,该算法利用给定的二叉树后序和中序遍历序列来重建二叉树。通过分析序列特性,文章详细解释了如何确定根节点,并递归地构建左子树和右子树。代码实现部分展示了使用HashMap加速查找过程的方法。
253

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



