Leetcode 驗證二叉搜索樹
阿新 • • 發佈:2018-09-05
__init__ 列表 roo 排序 spa != 當前 是否 treenode
給定一個二叉樹,判斷其是否是一個有效的二叉搜索樹。
假設一個二叉搜索樹具有如下特征:
- 節點的左子樹只包含小於當前節點的數。
- 節點的右子樹只包含大於當前節點的數。
- 所有左子樹和右子樹自身必須也是二叉搜索樹。
示例 1:
輸入: 2 / 1 3 輸出: true
示例 2:
輸入: 5 / 1 4 / 3 6 輸出: false
解釋: 輸入為: [5,1,4,null,null,3,6]。 根節點的值為 5 ,但是其右子節點值為 4 。
這道題我想的解答方案是錯誤的,後來參考了別人的
# Definition for a binary tree node.# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ def test(root): l=[]if not root: return [] l+=test(root.left) # 類似於中序遍歷 l.append(root.val) l+=test(root.right) return l res=test(root) ‘‘‘左子樹只包含小於該結點的數,右子樹只包含大於該結點的數 即父節點永遠大於左結點,小於右結點, 若是二叉搜索樹,最後的列表必然是升序排列的, 故將res和排序後的res比較,不相等則不是‘‘‘ if res!=sorted(list(set(res))): return False else: return True
Leetcode 驗證二叉搜索樹