题目描述:
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 thanthe 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.
Example 1:
2
/ \
1 3
Input: [2,1,3]
Output: true
Example 2:
5
/ \
1 4
/ \
3 6
Input: [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.
中文理解:
给定一个二叉搜索树,判断该树是不是满足二叉搜索树的条件。
解题思路:
可以得到中序遍历的序列,如果递增序列就满足条件,否则不满足条件,或者按照定义,左右子树的定义进行递归。
代码(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) {
if (root == null) return true;
return valid(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
public boolean valid(TreeNode root, long low, long high) {
if (root == null) return true;
if (root.val <= low || root.val >= high) return false;
return valid(root.left, low, root.val) && valid(root.right, root.val, high);
}
}
博客围绕判断二叉树是否为有效二叉搜索树展开。先给出英文题目描述,后有中文理解,即判断树是否满足二叉搜索树条件。解题思路一是获取中序遍历序列,若递增则满足;二是按定义对左右子树递归判断,还给出了 Java 代码。

被折叠的 条评论
为什么被折叠?



