Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

98. Validate Binary Search Tree #145

Open Tcdian opened 4 years ago

Tcdian commented 4 years ago

98. Validate Binary Search Tree

给定一个二叉树,判断其是否是一个有效的二叉搜索树。

假设一个二叉搜索树具有如下特征:

Example 1

    2
   / \
  1   3

Input: [2,1,3]
Output: true

Example 2

    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.
Tcdian commented 4 years ago

Solution

/**
 * 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 prevVal = -Infinity;
    let result = true;
    inOrderTravel(root);
    return result;
    function inOrderTravel(root) {
        if (!result || root === null) {
            return;
        }
        inOrderTravel(root.left);
        if (prevVal >= root.val) {
            result = false;
            return;
        }
        prevVal = root.val;
        inOrderTravel(root.right);
    }
};