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

题目

根据一棵树的中序遍历与后序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
Leetcode 106. 从中序与后序遍历序列构造二叉树_第1张图片

解法

感觉跟 Leetcode 105. 从前序与中序遍历序列构造二叉树 差不多,换汤不换药。

详情可以看我上一篇博客:https://blog.csdn.net/LetJava/article/details/95812161

跟上一题的区别就是 root 节点改到了后序遍历数组的最后而已。

代码

/**
 * 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) {
        return buildTree(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
    }
    
    private TreeNode buildTree(int[] inorder, int il, int ir, int[] postorder, int pl, int pr) {
        if(pr < pl) return null;
        if(pr == pl) return new TreeNode(postorder[pl]);

        int rootVal = postorder[pr];
        int index = -1;
        for(int i = il; i <= ir; i ++) {
            if(inorder[i] == rootVal) {
                index = i;
                break;
            }
        }
        
        if(index == -1) {
            throw new RuntimeException("不能构造出二叉树!");
        }
        
        TreeNode root = new TreeNode(rootVal);
        if(index > il) {
            root.left = buildTree(inorder, il, index - 1, postorder, pl, pl + index - il - 1);
        }
        
        if(index < ir) {
            root.right = buildTree(inorder, index + 1, ir, postorder, pl + index - il, pr - 1);
        }
        
        return root;
    }
    
}

结果

Leetcode 106. 从中序与后序遍历序列构造二叉树_第2张图片

你可能感兴趣的:(leetcode)