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

[LeetCode] Validate Binary Search Tree

时间:2015-01-20 13:36:44      阅读:172      评论: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.

思路一:因为二查搜索树的中序遍历可以得到一个有序的序列。所以我们中序遍历二叉树,用pre_value记录中序遍历上一个节点的值,然后判断每个点的值是否大于前一个节点的值。假设pre_value = INT_MIN,这种情况在所给二叉树只有一个根节点root,且root->val == INT_MIN的情况下WA。改变pre_value = LONG_MIN后AC。、

  时间复杂度O(N),空间复杂度O(N).

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     bool isValidBST(TreeNode *root) {
13         stack<TreeNode *> s;
14         TreeNode *p = root;
15         long pre_value = LONG_MIN;
16         
17         while (!p || !s.empty()) {
18             if (!p) {
19                 s.push(p);
20                 p = p->left;
21             } else {
22                 p = s.top();
23                 if (p->val <= pre_value)
24                     return false;
25                 pre_value = p->val;
26                 s.pop();
27                 p = p->right;
28             }
29         }
30         
31         return true;
32     }
33 };

 

思路二:递归的方法。时间复杂度O(n),空间复杂度O(logN)

  

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     bool isValidBST(TreeNode *root) {
13         return isValidBST(root, LONG_MIN, LONG_MAX);
14     }
15     bool isValidBST(TreeNode *root, long lower_value, long upper_value) {
16         if (root == NULL) return true;
17         
18         return root->val > lower_value && root->val < upper_value
19                && isValidBST(root->left, lower_value, root->val)
20                && isValidBST(root->right, root->val, upper_value);
21     }
22 };

 

[LeetCode] Validate Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/vincently/p/4235672.html

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