LeetCode 98. Validate Binary Search Tree
原题链接在这里:https://leetcode.com/problems/validate-binary-search-tree/
题目:
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.
题解:
根据BST特性递归调用原函数,如果出现root.val >= max 或者root.val <= min的情况return false.
Note: 初始的max 和 min 要设成long 型的最大最小值,因为边界的corner case. 若是用Integer.MAX_VALUE. 并且数只有一个节点,刚开始若root.val = Integer.MAX_VALUE, 会返回false. 其实应该返回true.
Time Complexity: O(n). Space: O(logn).
AC Java:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isValidBST(TreeNode root) { return isValidHelper(root, Long.MIN_VALUE, Long.MAX_VALUE); } private boolean isValidHelper(TreeNode root, long min, long max){ if(root == null){ return true; } if(root.val >= max || root.val<= min){ return false; } return isValidHelper(root.left, min, root.val) && isValidHelper(root.right, root.val, max); } }
AC C++:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 bool isValidBST(TreeNode* root) { 15 return isValidDfs(root, LONG_MIN, LONG_MAX); 16 } 17 18 private: 19 bool isValidDfs(TreeNode* root, long min, long max){ 20 if(!root){ 21 return true; 22 } 23 24 if(root->val <= min || root->val >= max){ 25 return false; 26 } 27 28 return isValidDfs(root->left, min, root->val) && isValidDfs(root->right, root->val, max); 29 } 30 };
另外一种方法是做inorder traverse, 若是出现逆序,就返回false.
Time Complexity: O(n). Space: O(logn).
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 TreeNode prev; 12 public boolean isValidBST(TreeNode root) { 13 if(root == null){ 14 return true; 15 } 16 //左边 17 if(!isValidBST(root.left)){ 18 return false; 19 } 20 //中间 21 if(prev != null && prev.val >= root.val){ 22 return false; 23 } 24 prev = root; 25 //右边 26 if(!isValidBST(root.right)){ 27 return false; 28 } 29 return true; 30 } 31 }
类似Find Mode in Binary Search Tree, Minimum Absolute Difference in BST.