Leetcode 98 Validate Binary Search Tree
阿新 • • 發佈:2020-10-25
題目介紹
判斷給定二叉樹是否為一棵二叉搜尋樹。
Examples:
2
/ \
1 3
Input: [2,1,3]
Output: true
5
/ \
1 4
/ \
3 6
Input: [5,1,4,null,null,3,6]
Output: false
Solution
僅僅使用遞迴判斷左子樹是否平衡或者右子樹是否平衡有可能出現右子樹中的值比當前根節點還要小。利用先序遍歷,平衡二叉樹的結果是一個升序序列,因此,只要判斷新增加的節點是否比前一節點大即可。
class Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ max_val = [float('-inf')] def helpfunc(root): if not root: return True if not helpfunc(root.left): return False if root.val <= max_val[0]: return False else: max_val[0] = root.val if not helpfunc(root.right): return False return True return helpfunc(root)
一種更優雅的方式,是採用遞迴,但是每次傳入範圍:
class Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ min_value, max_value = float('-inf'), float('inf') def helpfunc(root, min_value, max_value): if not root: return True if root.val <= min_value or root.val >= max_value: return False return helpfunc(root.left, min_value, root.val) and helpfunc(root.right, root.val, max_value) return helpfunc(root, min_value, max_value)