mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
@ -254,21 +254,58 @@ public:
|
|||||||
|
|
||||||
|
|
||||||
Java:
|
Java:
|
||||||
```java
|
|
||||||
class Solution {
|
|
||||||
public boolean isValidBST(TreeNode root) {
|
|
||||||
return isValidBST_2(root, Long.MIN_VALUE, Long.MAX_VALUE);
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isValidBST_2 (TreeNode root, long lo, long hi) {
|
```Java
|
||||||
if (root == null) return true;
|
class Solution {
|
||||||
if (root.val >= hi || root.val <= lo) return false;
|
// 递归
|
||||||
return isValidBST_2(root.left,lo,root.val) && isValidBST_2(root.right,root.val,hi);
|
TreeNode max;
|
||||||
|
public boolean isValidBST(TreeNode root) {
|
||||||
|
if (root == null) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
// 左
|
||||||
|
boolean left = isValidBST(root.left);
|
||||||
|
if (!left) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// 中
|
||||||
|
if (max != null && root.val <= max.val) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
max = root;
|
||||||
|
// 右
|
||||||
|
boolean right = isValidBST(root.right);
|
||||||
|
return right;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Solution {
|
||||||
|
// 迭代
|
||||||
|
public boolean isValidBST(TreeNode root) {
|
||||||
|
if (root == null) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
Stack<TreeNode> stack = new Stack<>();
|
||||||
|
TreeNode pre = null;
|
||||||
|
while (root != null || !stack.isEmpty()) {
|
||||||
|
while (root != null) {
|
||||||
|
stack.push(root);
|
||||||
|
root = root.left;// 左
|
||||||
|
}
|
||||||
|
// 中,处理
|
||||||
|
TreeNode pop = stack.pop();
|
||||||
|
if (pre != null && pop.val <= pre.val) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
pre = pop;
|
||||||
|
|
||||||
|
root = pop.right;// 右
|
||||||
|
}
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user