LeetCode : 98. 驗證二叉搜索樹
給定一個二叉樹,判斷其是否是一個有效的二叉搜索樹。
假設一個二叉搜索樹具有如下特徵:
節點的左子樹只包含小於當前節點的數。
節點的右子樹只包含大於當前節點的數。
所有左子樹和右子樹自身必須也是二叉搜索樹。
示例 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
def Create_tree(root,list,i):
if i<len(list):
if not list[i]: return None # 返回值 == None,以下不必判斷
else:
root = TreeNode(list[i])
root.left = Create_tree(root.left,list,i*2+1)
root.right= Create_tree(root.right,list,i*2+2)
return root
return root
中序遍歷:遞歸+迭代
class Solution:
# 中序 遞歸遍歷
def isValidBST(self, root: TreeNode) -> bool:
res = []
def helper(root):
if not root: return None
helper(root.left)
res.append(root.val)
helper(root.right)
helper(root)
return res==sorted(res) and len(set(res))==len(res)
# 中序 迭代遍歷
def isValidBST2(self, root: TreeNode) -> bool:
res =[]
if not root: return res
stack =[]
p = root
while p or stack:
while p:
stack.append(p)
p=p.left
p=stack.pop()
res.append(p.val)
p = p.right
# return res
return res==sorted(res) and len(set(res))==len(res)
python 知識點: len(set(res))==len(res)
set 將列表轉換成元組同時去除其中的重複元素
測試代碼:
if __name__ == "__main__":
s = Solution()
nums= [5,1,4,None,None,3,6]
root = Create_tree(None,nums,0)
r = s.isValidBST(root)
print(r)