98. Validate Binary Search Tree

题目

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

Example 1:

    2
   / \
  1   3
Binary tree  [2,1,3] , return true.

Example 2:

    1
   / \
  2   3
Binary tree  [1,2,3] , return false.

分析

判断是否二叉查找树,通过递归后序遍历,记录左右子树的最大最小值,与根节点的值一起判断是否符合二叉查找树的规定。

扫描二维码关注公众号,回复: 47109 查看本文章
class Solution {
public:
    bool postOrder(TreeNode* root,int& subMin,int& subMax){
        if(root==NULL)//根节点为空或者到叶节点时,符合二叉查找树
            return true;
        int leftMin=INT_MAX,leftMax=INT_MIN;//记录左子树的最大最小元素
        int rightMin=INT_MAX,rightMax=INT_MIN;//记录右子树的最大最小元素
        bool left=postOrder(root->left,leftMin,leftMax);//判断左子树是否二叉查找树
        bool right=postOrder(root->right,rightMin,rightMax);//判断右子树是否二叉查找树
        subMin=min(min(leftMin,rightMin),root->val);//包括根节点计算整个子树的最大值和最小值
        subMax=max(max(leftMax,rightMax),root->val);
        if(!left||!right)//如果左子树或者右子树任一不是二叉查找树,则返回false
            return false;
        if((root->left==NULL||leftMax<root->val)&&(root->right==NULL||rightMin>root->val))//当左右子树非空且满足二叉查找树的规则时,返回true
            return true;
        else
            return false;
    }
    bool isValidBST(TreeNode* root) {
        int leftMin=INT_MAX,leftMax=INT_MIN;
        return postOrder(root,leftMin,leftMax);//后序遍历计算是否二叉查找树
    }
};


猜你喜欢

转载自blog.csdn.net/cuihaolong/article/details/80048693
今日推荐