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#
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 }