• 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
  • 相关阅读:
    DataTable中的增删改查
    如何修改SQLServer的登录验证模式为混合验证模式(转载)
    asp.net C# 技术小点
    利用JQuery动态删除Table表格的行和列
    ASP.NET利用JQuery中的Aajax实现JSON数据后台交互
    MySQL Explain 详解
    Python字符串操作
    Linux中last的用法及参数,查看登陆系统用户的信息
    fedora 16 mysql远程连接
    Linux下MySQL 5.5.21 服务器日志配置
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/3035559.html
Copyright © 2020-2023  润新知