思路
原题链接
- 题目给了中序遍历和后序遍历的结果数组
- 首先使用后序遍历来确定根节点的值,即root_val
- 根据root_val 构建二叉树
- 之后要确定root结点在左子树中的索引位置i_root_index,使用leftNum来保存左子树的长度值 leftNum = i_root_index - i_start
- 确定好以上的内容后,开始递归构建root.left and root.right
- 递归构建左子树的函数中的参数是:中序遍历数组,中序左子树开始位置,中序中左子树的截止位置,后序遍历数组,后序左子树开始位置,后序中左子树的截止位置
- 递归构建右子树的函数中的参数和以上类似:中序遍历数组,中序中右子树开始位置,中序右子树截止位置,后序遍历数组,后序中右子树开始位置,后序中右子树截止位置
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
return buildTreeHelper(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
}
private TreeNode buildTreeHelper(int[] inorder, int i_start, int i_end, int[] postorder, int p_start, int p_end){
//此处是终止条件
if(i_start > i_end) return null;
//首先寻找根节点root,其位置在后序遍历的最后面的位置
int root_val = postorder[p_end];
//使用寻找到的根节点建立二叉树
TreeNode root = new TreeNode(root_val);
//寻找左子树的范围,也就是左子树的长度leftNum
int i_root_index = 0;
for(int i = i_start; i <= i_end; i++){
if(root_val == inorder[i]){
//使用i_root_index来保存根节点在中序遍历中的索引位置
i_root_index = i;
//若寻找到左子树的范围值则直接break
break;
}
}
//使用leftNum保存左子树的长度值
int leftNum = i_root_index - i_start;
//开始递归构建左右子树
root.left = buildTreeHelper(inorder, i_start, i_root_index - 1, postorder, p_start, p_start + leftNum - 1);
root.right = buildTreeHelper(inorder, i_root_index + 1, i_end, postorder, p_start + leftNum, p_end - 1);
return root;
}
}