声明:本题及相关刷题笔记同步github之中,欢迎Fork & Star GitHub:https://github.com/HoqiheChen。如有不足之处,烦请改正。QQ Mail:851774342@qq.com
Description
Given a binary tree, determine if it is a valid binary search tree (BST).
Brief
判断一棵树是否为二叉搜索树。
Input
(1)
(2)
Output
(1)true
(2)false
Explanation
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.
Ideas
递归判断每个结点的子树是否为二叉搜索树。
需要加入两个参数,即每个结点的上限和下限。
Code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
if(root == null){
return true;
}
return isValid(root,null,null);
}
public boolean isValid(TreeNode root,Integer max,Integer min){
if(root == null){
return true;
}
if(max != null && max <= root.val){
return false;
}
if(min != null && min >= root.val){
return false;
}
return isValid(root.left,root.val,min) && isValid(root.right,max,root.val);
}
}
声明:本题及相关刷题笔记同步github之中,欢迎Fork & Star GitHub:https://github.com/HoqiheChen。如有不足之处,烦请改正。QQ Mail:851774342@qq.com