题意:
根据一棵树的中序遍历与后序遍历构造二叉树。
思路:
后序遍历从后往前看,就是相当于一个前序遍历。从后往前一个个遍历,就相当于遍历了每个子树的根节点。根据这个根节点对中序遍历的数组进行划分即可。采用递归进行解题。
在构造子树的时候,注意先构造右子树,再构造左子树。可以理解为在后序遍历的数组中整个数组是先存储左子树的节点,再存储右子树的节点,最后存储根节点,我们从后往前遍历post数组,相当于反过来,就是要先建立右子树。
代码:
class Solution {
Map<Integer, Integer> map;
int postIndex;
public TreeNode buildTree(int[] inorder, int[] postorder) {
int len = inorder.length;
if(len == 0)
return null;
if(len == 1)
return new TreeNode(inorder[0]);
map = new HashMap<>();
postIndex = len-1;
for(int i = 0; i < len; i++)
{
map.put(inorder[i], i);
}
TreeNode res = fuc(0, len-1, inorder, postorder);
return res;
}
public TreeNode fuc(int l, int r, int[] inorder, int[] postorder){
if(l > r)
return null;
TreeNode newNode = new TreeNode(postorder[postIndex]);
System.out.println(newNode.val);
int inIndex = map.get(postorder[postIndex]);
postIndex--;
newNode.right = fuc(inIndex+1, r, inorder, postorder);
newNode.left = fuc(l, inIndex-1, inorder, postorder);
return newNode;
}
}
二叉树构造解析
本文介绍了一种根据中序和后序遍历结果构造二叉树的方法。通过递归方式,利用哈希映射提高查找效率,实现左右子树的构建。特别指出构造时应先建立右子树。
664

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



