• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ying_vincent
博客园    首页    新随笔    联系   管理    订阅  订阅

LeetCode: Validate Binary Search Tree

看了别人的代码

 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 dfs(TreeNode *root, int MIN, int MAX) {
13         if (!root) return true;
14         if (root->val > MIN && root->val < MAX && dfs(root->left, MIN, root->val) && dfs(root->right, root->val, MAX))
15             return true;
16         else return false;
17     }
18     bool isValidBST(TreeNode *root) {
19         // Start typing your C/C++ solution below
20         // DO NOT write int main() function
21         return dfs(root, INT_MIN, INT_MAX);
22     }
23 };

 自己另外写了个,比较好懂

 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     void dfs(TreeNode *root, TreeNode * &pre, bool &flag) {
13         if (!root) return;
14         dfs(root->left, pre, flag);
15         if (pre && pre->val >= root->val) {
16             flag = false;
17             return;
18         }
19         pre = root;
20         dfs(root->right, pre, flag);
21     }
22     bool isValidBST(TreeNode *root) {
23         // Start typing your C/C++ solution below
24         // DO NOT write int main() function
25         TreeNode *pre = NULL;
26         bool flag = true;
27         dfs(root, pre, flag);
28         return flag;
29     }
30 };

 C#

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left;
 6  *     public TreeNode right;
 7  *     public TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public bool IsValidBST(TreeNode root) {
12         return dfs(root, Int64.MinValue, Int64.MaxValue);
13     }
14     public bool dfs(TreeNode root, Int64 Min, Int64 Max) {
15         if (root == null) return true;
16         return root.val > Min && root.val < Max && dfs(root.left, Min, root.val) && dfs(root.right, root.val, Max);
17     }
18 }
View Code

 

posted @ 2013-04-22 15:00  ying_vincent  阅读(125)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3