98 Validate Binary Search Tree

判断一个二叉树是否为BST

BST 二叉搜索树,若左子树不空,左子树的所有节点的值小于根节点的值,若右子树不空,右子树的所有节点的值大于根节点的值,左右子树分别也为 BST

递归实现,faster than 100%

/**
 * 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) {
    return solver(root, null, null)
};
var solver = function(root, h, l){
    if(root === null) return true
    if((h !== null && root.val >= h) || (l !== null && root.val <= l)) return false
    return solver(root.left, root.val, l) && solver(root.right, h, root.val)
}

利用二叉树的中序遍历实现,faster than 21%

var isValidBST = function(root) {
    var res = inorderTraversal(root)
    for(var i = 0; i < res.length; i++){
        if(res[i] >= res[i + 1]) return false
    }
    return true
};
var inorderTraversal = function(root){
    var res = []
    var stack = []
    while (root !== null || stack.length !== 0){
        if (root !== null){
            stack.push(root)
            root = root.left
        } else{
            root = stack.pop()
            res.push(root.val)
            root = root.right
        }
    }
    return res
}

你可能感兴趣的:(98 Validate Binary Search Tree)