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 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.
Example 1:
1 | Input: root = [2,1,3] |
Example 2:
1 | Input: root = [5,1,4,null,null,3,6] |
判斷某樹是不是二元樹,要符合條件:
- 任一個節點的左子樹的所有節點值均小於該節點自身的值
- 任一個節點的右子樹的所有節點值均大於該節點自身的值
- 二元搜尋樹的左子樹和右子樹也都是二元搜尋樹
那就遞迴吧。
1 | T: O(n), S: O(1) |
如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)