# 题目

• 节点的左子树中的值要严格小于该节点的值。
• 节点的右子树中的值要严格大于该节点的值。
• 左右子树也必须是二叉查找树。
• 一个节点的树也是二叉查找树。

2 / 1 4 / 3 5 上述这棵二叉树序列化为 {2,1,4,#,#,3,5}.

# 代码

```/**
* Definition of TreeNode:
* public class TreeNode {
*     public int val;
*     public TreeNode left, right;
*     public TreeNode(int val) {
*         this.val = val;
*         this.left = this.right = null;
*     }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: True if the binary tree is BST, or false
*/

public boolean isValidBST(TreeNode root) {
// Just use the inOrder traversal to solve the problem.
if (root == null) {
return true;
}

return dfs(root, Long.MIN_VALUE, Long.MAX_VALUE);
}

private boolean dfs(TreeNode root, long min, long max) {
if(root == null)
return true;

if(root.val <= min || root.val >= max)
return false;

return dfs(root.left, min, root.val) && dfs(root.right, root.val, max);
}
}```

381 篇文章35 人订阅

0 条评论

## 相关文章

2884

1672

### LeetCode 144. Binary Tree Preorder Traversal题目分析代码

Given a binary tree, return the preorder traversal of its nodes' values. For ex...

962

712

2203

2514

### 111.Minimum Depth of Binary Tree(Tree-Easy)

Given a binary tree, find its minimum depth. The minimum depth is the number of ...

2149

1125