题目描述:
给出一棵树的中序遍历和后序遍历,请构造这颗二叉树
注意:
保证给出的树中不存在重复的节点
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
解题思路:
- 涉及到二叉树的问题都是考虑用递归树来解决
- 观察中序遍历和后续遍历,我们不难发现后序遍历中的最后一位就是根节点的值
- 找到根节点的之后,我们再在前序遍历数组中找到根节点的值,将其一分为二,剩下的事情就交给递归来做
代码如下:
public TreeNode buildTree(int[] inorder, int[] postorder) {
int inLength = inorder.length;
int postLength = postorder.length;
// 对输入的数组进行简单的判断
if(inLength != postLength) return null;
// 递归结束的条件
if(inLength < 1 || postLength < 1) return null;
// 递归体
TreeNode root = new TreeNode(postorder[postLength - 1]);
for(int i = 0; i < inLength; i++){
if(inorder[i] == postorder[postLength - 1]){
root.left = buildTree(Arrays.copyOfRange(inorder,0,i),
Arrays.copyOfRange(postorder,0,i));
root.right = buildTree(Arrays.copyOfRange(inorder,i + 1,inLength),
Arrays.copyOfRange(postorder,i,postLength - 1));
}
}
return root;
}