0
点赞
收藏
分享

微信扫一扫

LeetCode 106 从中序与后序遍历序列构造二叉树

半秋L 2022-02-19 阅读 63

思路

原题链接

  1. 题目给了中序遍历和后序遍历的结果数组
  2. 首先使用后序遍历确定根节点的值,即root_val
  3. 根据root_val 构建二叉树
  4. 之后要确定root结点左子树中的索引位置i_root_index,使用leftNum保存左子树的长度值 leftNum = i_root_index - i_start
  5. 确定好以上的内容后,开始递归构建root.left and root.right
  6. 递归构建左子树的函数中的参数是:中序遍历数组,中序子树开始位置,中序中子树的截止位置,后序遍历数组,后序子树开始位置,后序中子树的截止位置
  7. 递归构建右子树的函数中的参数和以上类似:中序遍历数组,中序中子树开始位置,中序子树截止位置,后序遍历数组,后序中子树开始位置,后序中子树截止位置
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;
    }    
}
举报

相关推荐

0 条评论