剑指 Offer 33. 二叉搜索树的后序遍历序列 树的遍历

地址  https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/

输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。
假设输入的数组的任意两个数字都互不相同。

参考以下这颗二叉搜索树:

     5
    / \
   2   6
  / \
 1   3

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

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

提示:
数组长度 <= 1000

 

解答

二叉树 的性质是 左子树左右节点都比根节点小  右子树都比根节点大

而后继遍历  根节点在最后

那么我获得一段数据后,得出根节点,

然后检查他之前的数据是否分为两段大于与小于根节点(第一棵树的例子)

或者全部小于根节点(第二棵树)

或者全部大于根节点(第三棵树)

检查完当前数据后,根据大于根节点和小于根节点将数据分为左子树与右子树两段继续检测(递归)

代码如下

class Solution {
public:
    bool dfs(const vector<int>& postorder, int l, int r) {
        if (l >= r) return true;
        int i = r - 1;
        while (i >= l && postorder[i] >= postorder[r]) {
            i--;
        }
        int nextidx = i;
        //找到分割点之后,分割点再往前 如果还有比根大的节点那么返回false
        while (i >= l) {
            if (postorder[i] >= postorder[r]) return false;
            i--;
        }

        return dfs(postorder, l, nextidx) && dfs(postorder, nextidx + 1, r-1);
    }

    bool verifyPostorder(vector<int>& postorder) {
        if (postorder.empty()) return true;
        return dfs(postorder, 0, postorder.size() - 1);
    }
};

 

 

我的视频题解空间 

posted on 2021-01-30 22:16  itdef  阅读(114)  评论(0)    收藏  举报

导航