您的位置:首页 > 其它

【LeetCode】Validate Binary Search Tree

2014-07-11 11:16 337 查看
Validate Binary Search Tree

Total Accepted: 15264 Total Submissions: 60008 My Submissions

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.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

【解题思路】

1、二叉搜索树的基本判断,左孩子比根值小,右孩子比根值大。

2、按照这个思路,默认的最大最小值是int的值范围。

3、递归判断,每次判断左右孩子的值和最大最小值的比较。

4、一直到根为空,递归结束。

Java AC 416ms

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isValidBST(TreeNode root) {
        return dfs(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
    }
    public boolean dfs(TreeNode root, int min, int 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);
    }
}


Python AC 308ms

# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param root, a tree node
    # @return a boolean
    def isValidBST(self, root):
        max_val = 2**31
        return self.dfs(root, -max_val, max_val)

    def dfs(self, root, min_val, max_val):
        if root is None:
            return True
        if root.val <= min_val or root.val >= max_val:
            return False
        return self.dfs(root.left, min_val, root.val) 
				and self.dfs(root.right, root.val, max_val)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: