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

Leetcode 98 Validate Binary Search Tree

时间:2015-07-03 13:55:42      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

BST 其实就是一个中跟遍历,中跟遍历后的顺序应该是排好序的!!!!

 

 1 class Solution {
 2 public:
 3     bool isValidBST(TreeNode* root) {
 4         if (root == NULL)
 5             return true;
 6         if (root->left == NULL && root->right == NULL)
 7             return true;
 8         stack<TreeNode*> s;
 9         TreeNode* p = root; 
10         int left,flag;
11         flag = 0;
12         while(p)
13         {
14             while(p)
15             {
16                 s.push(p);
17                 p = p->left;
18             }
19             while(!s.empty())
20             {
21                 TreeNode * cur = s.top();
22                 s.pop();
23                 if(flag == 0)
24                 {
25                     flag = 1;
26                     left = cur->val;
27                 }
28                 else if(cur->val <= left)
29                     return false;
30                 left = cur->val;
31                 if(cur->right)
32                 {
33                     p = cur->right;
34                     break;
35                 }
36 
37             }
38             
39         }
40         return true;
41     }
42 };

 递归的方法:

 

引入全局变量

 1 class Solution {
 2 public:
 3     bool isValidBST(TreeNode *root) {
 4         static int m = INT_MIN;
 5         if(root == NULL) return true;
 6         if(!isValidBST(root->left)) return false;
 7         if(!(root->val > m)) {
 8             return false;
 9         }
10         m = root->val;
11         return isValidBST(root->right);
12     }
13 };

 

Leetcode 98 Validate Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/zhuguanyu33/p/4618395.html

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