您的位置:首页 > 编程语言 > Python开发

【LeetCode】Validate Binary Search Tree 解题报告(Java & Python)

2017-04-17 13:06 756 查看

【LeetCode】Validate Binary Search Tree 解题报告(Java & Python)

标签(空格分隔): LeetCode

题目地址:https://leetcode.com/problems/validate-binary-search-tree/#/description

题目描述:

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.

Example:

2
/ \
1   3

Binary tree [2,1,3], return true.

1
/ \
2   3

Binary tree [1,2,3], return false.


Ways

判断一棵树是不是BST,那么按照定义,左子树的值要在(min,mid)之间,右子树的值在(mid,max)之间,这个mid值并不是中位数而是当前节点的值。这么一想,就可以很快的判断是不是符合BST的定义了。

/**
* 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) {
return isValid(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
public boolean isValid(TreeNode root, long min, long max){
if(root == null){
return true;
}
long mid = root.val;
if(mid <= min || mid >= max){
return false;
}
return isValid(root.left, min, mid) && isValid(root.right, mid, max);
}
}


二刷,python

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

class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return self.valid(root, float('-inf'), float('inf'))

def valid(self, root, min, max):
if not root: return True
if root.val >= max or root.val <= min:
return False
return self.valid(root.left, min, root.val) and self.valid(root.right, root.val, max)


Date

2017 年 4 月 17 日

2018 年 3 月 23 日 ———— 科目一考了100分哈哈哈哈~嗝~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: