98. Validate Binary Search Tree
Leetcode
https://leetcode.com/problems/validate-binary-search-tree/
題目
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:

Input: root = [2,1,3]
Output: trueExample 2:

Input: root = [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.解答
方法一
dfs preorder
在每一個節點中往上傳 isValid, min, max,每個節點再跟左右節點的最大最小值比較看是否為 isValid
Runtime: 156 ms, faster than 5.10% of JavaScript online submissions for Validate Binary Search Tree.
Memory Usage: 47.7 MB, less than 7.92% of JavaScript online submissions for Validate Binary Search Tree.
方法二
DFS preorder
在遍歷每一個節點時,檢查其值是否在上下限的範圍中 (low: 下限、high: 上限)
Example 2.
5 => low: 負無限大, high: 正無限大
1 => low: 負無限大, high: 5
4 => low: 5, high: 正無限大 => isValid === false
3 => low: 負無限大, high: 4
6 => low: 4, high: 正無限大
Runtime: 56 ms, faster than 99.72% of JavaScript online submissions for Validate Binary Search Tree.
Memory Usage: 46.3 MB, less than 54.66% of JavaScript online submissions for Validate Binary Search Tree.
方法三
BFS preorder
用 stack 採用先右後左 push 的方式
Runtime: 98 ms, faster than 52.66% of JavaScript online submissions for Validate Binary Search Tree.
Memory Usage: 46.9 MB, less than 16.01% of JavaScript online submissions for Validate Binary Search Tree.
方法四
DFS inorder
採用 inorder 的好處就是只要判斷每個元素的值都大於前一個元素就好
Ex.
input => [4, 2, 5, 1, 6]
after inorder => [1, 2, 6, 4, 5]
這時只要判斷是不是每個元素的值都大於前一個 => 發現 6 大於 4 => isValid === false
Runtime: 60 ms, faster than 99.37% of JavaScript online submissions for Validate Binary Search Tree.
Memory Usage: 46.1 MB, less than 81.02% of JavaScript online submissions for Validate Binary Search Tree.
方法五
BFS inorder
Runtime: 142 ms, faster than 8.16% of JavaScript online submissions for Validate Binary Search Tree.
Memory Usage: 46.6 MB, less than 34.92% of JavaScript online submissions for Validate Binary Search Tree.
Last updated