LeetCode算法笔记–Day49
98. Validate Binary Search Tree
Given a binary tree, determine if it is a valid binary search tree (BST).  
example:  
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 
 |     2/ \
 1   3
 
 Input: [2,1,3]
 Output: true
 
 5
 / \
 1   4
 / \
 3   6
 
 Input: [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.
 
 | 
Analyse:
- 二叉搜索树「中序遍历」得到的值构成的序列一定是升序的,这启示我们在中序遍历的时候实时检查当前节点的值是否大于前一个中序遍历到的节点的值即可。
- 时间复杂度 : O(n),其中 n 为二叉树的节点个数。二叉树的每个节点最多被访问一次,因此时间复杂度为 O(n)。
- 空间复杂度 : O(n),其中 n 为二叉树的节点个数。栈最多存储 n 个节点,因此需要额外的 O(n)的空间。
 
My Answer:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 
 | /*** Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
 /**
 * @param {TreeNode} root
 * @return {boolean}
 */
 var isValidBST = function(root) {
 let stack = [];
 let inorder = -Infinity;
 
 while (stack.length || root !== null) {
 while (root !== null) {
 stack.push(root);
 root = root.left;
 }
 root = stack.pop();
 // 如果中序遍历得到的节点的值小于等于前一个 inorder,说明不是二叉搜索树
 if (root.val <= inorder) return false;
 inorder = root.val;
 root = root.right;
 }
 return true;
 };
 
 |