ð 98. éªè¯äºåæ玢æ
2022幎10æ10æ¥
- algorithm
ð 98. éªè¯äºåæ玢æ
éŸåºŠ: ð
é®é¢æè¿°
è§£æ³ 1 - éåœ
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
TreeNode pre = null;
public boolean isValidBST(TreeNode root) {
// æè·¯ïŒ
// äžåºéå - äºåæ玢æ¶æåº
return mySol(root);
}
private boolean mySol(TreeNode root) {
// éåœç»æ¢æ¡ä»¶
if(root == null) {
return true;
}
boolean left = mySol(root.left);
if(!left) {
return false;
}
int cur = root.val;
if(pre != null && cur <= pre.val) {
return false;
}
pre = root;
boolean right = mySol(root.right);
return right;
}
}
èŸåº 1
è§£æ³ 2 - è¿ä»£
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
// æè·¯ïŒ
// è¿ä»£
LinkedList<TreeNode> stack = new LinkedList<>();
TreeNode pre = null;
TreeNode cur = root;
while(cur != null || !stack.isEmpty()) {
while(cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
if(pre != null && cur.val <= pre.val) {
return false;
}
pre = cur;
cur = cur.right;
}
return true;
}
}