node遍历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.

    分析:先用中序遍历记下全部节点,然后判断此数组是否是已排序的。

    代码如下:

    每日一道理
那蝴蝶花依然花开花落,而我心中的蝴蝶早已化作雄鹰飞向了广阔的蓝天。

    void getroot(TreeNode *root,vector<int> &result)
    {
        if(root->left!=NULL)
        {
            getroot(root->left,result);
        }
        result.push_back(root->val);
        if(root->right!=NULL)
        {
            getroot(root->right,result);
        }
        return;
    }
    bool isValidBST(TreeNode *root) {
        if(root==NULL)return true;
        vector<int> result;
        getroot(root,result);
        for(int i=1;i<result.size();i++)
        {
            if(result[i-1]>=result[i])
            {
                return false;
            }
        }
        return true;
    }

文章结束给大家分享下程序员的一些笑话语录: 祝大家在以后的日子里. 男生象Oracle般健壮; 女生象win7般漂亮; 桃花运象IE中毒般频繁; 钱包如Gmail容量般壮大, 升职速度赶上微软打补丁 , 追女朋友像木马一样猖獗, 生活像重装电脑后一样幸福, 写程序敲代码和聊天一样有**。

--------------------------------- 原创文章 By
node和遍历
---------------------------------

原文地址:https://www.cnblogs.com/jiangu66/p/3111496.html