LeetCode 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.


思路

开始觉得这题目应该挺简单,直接递归左右子树,后来发现这个思路有很大的问题,只是保证左右子节点满足条件,而无法保证左子树的所有元素小于根节点(或者右子树所有元素大于根节点)。
这样的话可以想到用中序遍历来遍历所有节点,用递归实现中序遍历。
先遍历左子树,左子树不满足条件则返回false;
再查看根节点,如果根节点的值小于等于前面的部分则返回false;
最后遍历右子树。
二叉搜索树的中序遍历是一个递增的序列,所以这里用pre来表示中序遍历时当前结点前面的值,保证后面的值都比前面要小。


代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* pre=NULL;
    bool isValidBST(TreeNode* root) {
        if(root==NULL)
            return true;
        return inOrder(root);
    }
    bool inOrder(TreeNode* root) {
        if(root==NULL)
            return true;
        if(!inOrder(root->left)) return false; //遍历左子树

        if(pre != NULL && root->val <= pre->val) //查看根节点
            return false;
        pre = root;
        return inOrder(root->right); //遍历右子树
    }

};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值