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.

 判断是否是二叉搜索树有陷阱:http://blog.csdn.net/sgbfblog/article/details/7771096

C++实现代码如下,使用的是中序遍历是否为递增的序列来判断:

#include<iostream>
#include<new>
#include<vector>
#include<climits>
using namespace std;

//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)
    {
        if(root==NULL)
            return true;
        vector<int> rvec;
        preorder(root,rvec);
        size_t i;
        int max;
        if(rvec.size())
            max=rvec[0];
        for(i=1;i<rvec.size();i++)
        {
            if(rvec[i]>max)
            {
                max=rvec[i];
            }
            else
                return false;
        }
        return true;
    }
    void preorder(TreeNode *root,vector<int> &rvec)
    {
        if(root)
        {
            preorder(root->left,rvec);
            rvec.push_back(root->val);
            preorder(root->right,rvec);
        }
    }
    void createTree(TreeNode *&root)
    {
        int i;
        cin>>i;
        if(i!=0)
        {
            root=new TreeNode(i);
            if(root==NULL)
                return;
            createTree(root->left);
            createTree(root->right);
        }
    }
};

int main()
{
    Solution s;
    TreeNode *root;
    s.createTree(root);
    cout<<s.isValidBST(root)<<endl;
}

错误的方法:

#include<iostream>
#include<new>
#include<vector>
using namespace std;

//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)
    {
        if(root==NULL)
            return true;
        if(root->left&&root->right)
            return (root->left->val<root->val)&&(root->val<root->right->val)&&isValidBST(root->left)&&isValidBST(root->right);
        else if(root->left)
            return (root->left->val<root->val)&&isValidBST(root->left);
        else if(root->right)
            return (root->val<root->right->val)&&isValidBST(root->right);
    }
    void createTree(TreeNode *&root)
    {
        int i;
        cin>>i;
        if(i!=0)
        {
            root=new TreeNode(i);
            if(root==NULL)
                return;
            createTree(root->left);
            createTree(root->right);
        }
    }
};

int main()
{
    Solution s;
    TreeNode *root;
    s.createTree(root);
    cout<<s.isValidBST(root)<<endl;
}

 

时间: 2024-10-04 01:51:47

Validate Binary Search Tree的相关文章

Geeks 面试题之Optimal Binary Search Tree

Dynamic Programming | Set 24 (Optimal Binary Search Tree) Given a sorted array keys[0.. n-1] of search keys and an array freq[0.. n-1] of frequency counts, where freq[i] is the number of searches to keys[i]. Construct a binary search tree of all keys

算法:uva-10304 Optimal Binary Search Tree(区间dp)

题意 给一个序列即可 S = (e1,e2,...,en),且e1<e2<..<en.要把这些序列构成一个二叉搜索 树. 二叉搜索树是具有递归性质的,且若它的左子树不空,则左子树上所有结点的值均小于它的根结点的 值: 若它 的右子树不空,则右子树上所有结点的值均大于它的根结点的值. 因为在实际应用中,被访 问频率越高的元素,就应该越接近根节点,这样才能更加节省查找时间. 每个元素有一个访问频率f(ei) ,当元素位于深度为k的地方,那么花费cost(ei) = k. 所有节点的花费和访问

二叉查找树(binary search tree)详解

二叉查找树(Binary Search Tree),也称二叉排序树(binary sorted tree),是指一棵空树或者具有下列性质的二叉树: 若任意节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值 任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值 任意节点的左.右子树也分别为二叉查找树 没有键值相等的节点(no duplicate nodes) 本文地址:http://www.cnblogs.com/archimedes/p/binary-search-tree

[LeetCode]235.Lowest Common Ancestor of a Binary Search Tree

题目 Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: "The lowest common ancestor is defined between two nodes v and w as the lowest node in T that h

[LeetCode]173.Binary Search Tree Iterator

[题目] Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. Calling next() will return the next smallest number in the BST. Note: next() and hasNext() should run in average O(1) time and

[LeetCode]109.Convert Sorted List to Binary Search Tree

[题目] Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. [分析] 无 [代码] 在下面超时的代码上进行改进:把链表先转换为vector再进行操作. [LeetCode]108.Convert Sorted Array to Binary Search Tree /*******************************

[LeetCode]99.Recover Binary Search Tree

[题目] Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note:A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? [解析] O(n) 空间的解法是,开一个指针数组

[LeetCode]108.Convert Sorted Array to Binary Search Tree

[题目] Given an array where elements are sorted in ascending order, convert it to a height balanced BST. [分析] 二分法,以中间元素i为根节点[start,i-1]递归构建左子树,[i+1,end]递归构建右子树 [代码] /********************************* * 日期:2014-12-28 * 作者:SJF0115 * 题目: 108.Convert Sorte

Recover Binary Search Tree

Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note:A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?   confused what "{1,#,2,3}&qu