題目
原題頁面:https://leetcode.com/problems/validate-binary-search-tree/
題目型別:Tree, Depth-first Search
難度評價:Medium
類似題目:(M) Binary Tree Inorder Traversal
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.
confused what
"{1,#,2,3}"means?OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}".
分析
檢查一顆二叉樹是不是有效的二叉搜尋樹BST。注意BST的定義,不僅僅左孩子結點的值比當前結點小,左子樹上所有結點的值都要比當前結點小(BST跟heap是不同,heap只要求每個節點和它的直接孩子節點之間滿足大小關係即可)。右子樹上所有結點的值則都要比當前結點大。使用遞迴檢查每一棵子樹是不是BST,然後回溯的時候將檢查結果,以及當前子樹的最大和最小結點值返回給上一層遞迴。注意Python的return是可以返回一個元組的,相當於可以同時return多個變數,非常方便。
程式碼
1 | class Solution: |
本文地址:https://xnerv.wang/zh-tw/leetcode-validate-binary-search-tree/
