動態(tài)網(wǎng)站沒有數(shù)據(jù)庫怎么做產(chǎn)品推廣策劃書
給你一個二叉樹的根節(jié)點 root ,判斷其是否是一個有效的二叉搜索樹。
有效 二叉搜索樹定義如下:
節(jié)點的左子樹
只包含 小于 當前節(jié)點的數(shù)。
節(jié)點的右子樹只包含 大于 當前節(jié)點的數(shù)。
所有左子樹和右子樹自身必須也是二叉搜索樹。
英文題目
Given the root of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
The left subtreeof 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.
解題思路
畫了一個四層的二叉樹,發(fā)現(xiàn)遞歸方法是,左子樹的最右節(jié)點應(yīng)該比根節(jié)點小,右子樹的最左節(jié)點應(yīng)該比根節(jié)點大,基于此寫的代碼(事實上只要想著所有點,然后更新邊界,就可以不用重復(fù)遍歷來遞歸了)
AC代碼
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:def isValidBST(self, root: Optional[TreeNode]) -> bool:def judge(root):if root.left is None and root.right is None:return Trueif root is None:return Trueleft, right, leftflag, rightflag = root.left, root.right, True, Trueif left is not None:while left.right is not None:left = left.rightleftflag = root.val > left.val and judge(root.left)if right is not None:while right.left is not None:right = right.leftrightflag = root.val < right.val and judge(root.right)return leftflag and rightflagreturn judge(root)
官方題解
想到使用邊界后面思路就一下子通了
class Solution:def isValidBST(self, root: TreeNode) -> bool:stack, inorder = [], float('-inf')while stack or root:while root:stack.append(root)root = root.leftroot = stack.pop()# 如果中序遍歷得到的節(jié)點的值小于等于前一個 inorder,說明不是二叉搜索樹if root.val <= inorder:return Falseinorder = root.valroot = root.rightreturn True