码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 98. Validate Binary Search Tree

时间:2017-08-12 00:37:42      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:vector   void   ==   code   root   序列   color   could   level   

最简单的想法,中序遍历二叉树:

  • 递归中序遍历二叉树,得到一个中序遍历的序列
  • 判断这个序列是不是有序
class Solution {
public:
    void midTree(TreeNode * root, vector<int> & list)
    {
        if(root->left==NULL&&root->right==NULL)
        {
            list.push_back(root->val);
            return;
        }
         if(root->left)   
        midTree(root->left,list);
        list.push_back(root->val);
        if(root->right)
        midTree(root->right,list);
        
    }
    bool isValidBST(TreeNode* root) {
        vector<int> list;
        if(root==NULL)
            return true;
        midTree(root,list);
        
        for(int i=0;i<list.size()-1;i++)
        {
            cout<<list[i]<<endl;
            if(list[i+1]<=list[i])
                return false;
        }
        return true;
    }
};

 

或者直接判断:

  • 中序遍历,后面的节点要比前面遍历的节点值大
class Solution {
    // make sure it meets the BST not only at this level,
    // but also previous level
    // in-order access could produce a ascending order list
    // DFS
    bool helper(TreeNode * root) {
        if (root == NULL) {
            return true;
        }
        
        if (!helper(root->left)) {
            return false;
        }
        
        if (prev != NULL && prev->val >= root->val) {
            return false;
        }
        
        prev = root;
        
        return helper(root->right);
    }
public:
    TreeNode* prev = NULL;
    bool isValidBST(TreeNode* root) {
        return helper(root);
    }
};

  

 

leetcode 98. Validate Binary Search Tree

标签:vector   void   ==   code   root   序列   color   could   level   

原文地址:http://www.cnblogs.com/fanhaha/p/7348446.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!