98. Validate Binary Search Tree

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.

Example 1:

Input:
    2
   / \
  1   3
Output: true

Example 2:

    5
   / \
  1   4
     / \
    3   6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value
             is 5 but its right child's value is 4.

要驗證BST是否合理可以用inorder traversal去照著順序掃過每個node,同時記錄每個node的前一個node(prev),這樣在掃描每個node的時候跟前一個node的值比較,如果當前的值沒有大於前一個的值,那就是不合理,直接回傳false。

O(1) space usage的Morris Traversal不能遇到不合理的node就直接返回false,因為這樣中間暫時連接起來的node還沒斷開,必須所有的都掃描一遍然後斷開中間連接的地方,最後才返回true/false。

94. Binary Tree Inorder Traversal

Last updated

Was this helpful?