Sword refers to offer 33. Post-order traversal sequence of binary search tree

Sword refers to offer 33. Post-order traversal sequence of binary search tree

Title description

Insert picture description here

Problem-solving ideas

If only the post-order traversal sequence of the ordinary binary tree is known, the original binary tree cannot be restored, because the subscript range of the left and right subtrees cannot be determined.

But this question is a binary search tree, which can determine the subscript range of the left and right subtrees based on special properties.

In addition, if endOfLeftand indexwhen descending, we need to pay attention to the subscript cross-border issues, and the left margin here is not 0, but begin.

class Solution {
    
    
    public boolean verifyPostorder(int[] postorder) {
    
    
        if (postorder.length == 0) return true;
        return verifyPostorder(postorder, 0, postorder.length - 1);
    }

    //判断 postorder[begin...end] 是否是二叉搜索树的后序遍历结果
    public boolean verifyPostorder(int[] postorder, int begin, int end) {
    
    
        // base case
        if (begin >= end) return true;

        int endOfLeft = end;   //左子树的结束索引
        //左子树结束索引对应的元素是第一个比 postorder[end] 小的元素
        while (endOfLeft >= begin && postorder[endOfLeft] >= postorder[end]) endOfLeft--;
        //由于上面 while 遍历时,已经确保了右子树的所有元素都大于 postorder[end],所以要继续判断左子树的正确性
        int index = endOfLeft;
        while (index >= begin && postorder[index] < postorder[end]) index--;
        //首先要保证左子树的正确性,然后继续遍历左子树和右子树
        return (index + 1 == begin) && verifyPostorder(postorder, begin, endOfLeft) 
                && verifyPostorder(postorder, endOfLeft + 1, end - 1);
    }
}

Guess you like

Origin blog.csdn.net/cys975900334/article/details/115175564