您的位置:首页 > 其它

Validate Binary Search Tree

2016-07-08 10:29 281 查看
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 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.

A single node tree is a BST

Example

An example:

2
/ \
1   4
/ \
3   5

The above binary tree is serialized as
{2,1,4,#,#,3,5}
(in level order).

分析:

解题思路可以根据bst的特性来,对于每个子树,我们给他们一个最小和最大的范围。

public class Solution {
public boolean isValidBST(TreeNode root) {
return vilidateChild(root, Long.MIN_VALUE, Long.MAX_VALUE);
}

public boolean vilidateChild(TreeNode node, long min, long max) {
if (node == null) return true;
if (node.val < max && node.val > min) {
return vilidateChild(node.left, min, node.val) && vilidateChild(node.right, node.val, max);
} else {
return false;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: