首页 > 其他 > 详细

LeetCode OJ:Validate Binary Search Tree(合法的二叉搜索树)

时间:2015-10-25 14:55:16      阅读:249      评论: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.

一开始是这样做的:

 1 class Solution {
 2 public:
 3     bool isValidBST(TreeNode* root) {
 4        return checkValid(root, INT_MIN, INT_MAX);
 5     }
 6 
 7     bool checkValid(TreeNode * root, int left, int right)
 8     {
 9         if(root == NULL)
10             return true;
11         return(root->val > left && root->val < right && checkValid(root->left, left, root->val) ]
12             && checkValid(root->right, root->val, right));
13     }
14 };

然而并不能通过,因为leetCode增加了两个新的测试用例,把INT_MAX以及INT_MIN也囊括进去了。

那么就只好用中序遍历的方法来了,代码如下:

 1 class Solution {
 2 public:
 3     bool isValidBST(TreeNode* root) {
 4         inOrder(root);
 5         int sz = res.size();
 6         if(sz < 2) return true;
 7         for(int i = 1; i < sz; ++i){
 8             if(res[i] <= res[i - 1])
 9                 return false;
10         }
11         return true;
12     }
13 
14     void inOrder(TreeNode * root)
15     {
16         if(!root) return;
17         if(root->left) inOrder(root->left);
18         res.push_back(root->val);
19         if(root->right) inOrder(root->right);
20     }
21 private:
22     vector<int> res;
23 };

当然上面的也可以采用迭代的方式来做,代码这里就不贴了

LeetCode OJ:Validate Binary Search Tree(合法的二叉搜索树)

原文:http://www.cnblogs.com/-wang-cheng/p/4908685.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!