Sword Finger Offer 33. Post-order traversal sequence of binary search tree (C++) Auxiliary monotonic stack + post-order traversal reverse order

Enter an integer array to determine whether the array is the result of a post-order traversal of a binary search tree. If it is, it returns true, otherwise it returns false. Assume that any two numbers in the input array are different from each other.

Refer to the following binary search tree:

     5
    / \
   2   6
  / \
 1   3

Example 1:

输入: [1,6,3,2,5]
输出: false

Example 2:

输入: [1,3,2,6,5]
输出: true

Tip:
array length <= 1000

Problem-solving ideas:

Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here

class Solution {
    
    
public:
    bool verifyPostorder(vector<int>& postorder) {
    
    
        stack<int> stack;//借助一个单调栈 stack 存储值递增的节点;
        int root = INT_MAX;
        for(int i = postorder.size() - 1; i >= 0; i--) {
    
    
            if(postorder[i] > root) return false;//因为右子树时,root==INT_MAX
            //不会更新root的值,左子树时才可以更新root的值
            while(!stack.empty() && stack.top() > postorder[i])
            //每当遇到值递减的节点ri ,则通过出栈来更新节点 ri 的父节点 root ;
            //大于且最接近 ri的节点
            //栈非空 且 栈顶大于当前数组元素
            {
    
    
            	root = stack.top();//取栈顶值
                stack.pop();//出栈
                }
            stack.push(postorder[i]);//每一个元素都入栈
        }
        return true;//遍历数组后,若无异常就是二叉搜索树

    }
};

Complexity analysis:

Time complexity O(N): Traverse all nodes of the postorder, and each node is pushed/popped once, using O(N) time.
Space complexity O(N): In the worst case, the monotonic stack stores all nodes and uses O(N) extra space.

Author: jyd
link: https: //leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/solution/mian-shi-ti -33-er-cha-sou-suo-shu-de-hou-xu-bian-6/
Source: LeetCode (LeetCode)
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/qq_30457077/article/details/114988663