数据结构------Validate Binary Search Tree 验证二叉搜索树

 

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.

二叉搜索树定义:

二叉排序树或者是一棵空树,或者是具有下列性质的二叉树

(1)若左子树不空,则左子树上所有结点的值均小于或等于它的根结点的值;

(2)若右子树不空,则右子树上所有结点的值均大于或等于它的根结点的值;

(3)左、右子树也分别为二叉排序树;

    Example :

这里用中序遍历结果为:【1,3,4,6,7,8,10,13,14】,由此可见,用中序遍历搜索二叉树,遍历结果是从小到大排序的。

反例:

    10
   /  \
  4    15
 / \   / \
2   5 6   17       

由上图可得:15,6,17局部满足BST树,但是6<10,所以不是BST树,其中序遍历结果为:【2,4,5,10,6,15,17】,中序遍历结果不是从小到大排序的。
 思路:我们可以根据其中序遍历的特点来进行判断是否合法。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isValidBST(TreeNode *root) {
       //方法一:采用中序递归遍历,求得遍历结果,放入容器vals中,然后比较大小
        if (root==NULL)
            return true;
        vector<int> vals;
        inorder(root, vals);
        for (int i = 0; i < vals.size() - 1; ++i) {
            if (vals[i] >= vals[i + 1])//中序从小到大
                return false;
        }
        return true;
    }
    void inorder(TreeNode *root, vector<int> &vals) {//中序遍历
        if (root==NULL) return;
        inorder(root->left, vals);
        vals.push_back(root->val);
        inorder(root->right, vals);
        //方法二:采用中序根左右的递归遍历,同时判断是否合法,中序遍历结果从小到大排序
   /*     TreeNode* prev = NULL;
        return is_bst(root, prev);
    }
    bool is_bst(TreeNode* root, TreeNode*& prev){
        if(root == NULL) 
            return true;
        if(is_bst(root->left, prev)==NULL) 
            return false;
        if(prev != NULL && prev->val >= root->val) 
            return false;
        prev = root;
        return is_bst(root->right, prev); */
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值