1. 程式人生 > 其它 >SQL注入之MySQL注入

SQL注入之MySQL注入

leetcode98.驗證二叉搜尋樹

題目

給你一個二叉樹的根節點 root ,判斷其是否是一個有效的二叉搜尋樹。

有效 二叉搜尋樹定義如下:

節點的左子樹只包含 小於 當前節點的數。
節點的右子樹只包含 大於 當前節點的數。
所有左子樹和右子樹自身必須也是二叉搜尋樹。

用例

輸入:root = [2,1,3]
輸出:true
輸入:root = [5,1,4,null,null,3,6]
輸出:false
解釋:根節點的值是 5 ,但是右子節點的值是 4 。

求解

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isValidBST = function(root) {
    //二叉搜尋樹的中序遍歷必定是遞增序列
    let res = true
    let preVal = null
    midOrder(root)
    return res

    function midOrder(root){
        if(root==null||res==false){
            return
        }
        midOrder(root.left)
        if(preVal==null){
            preVal = root.val
        }else{
            if(preVal>=root.val){
                res=false
            }
            preVal = root.val
        }
        midOrder(root.right)
    }
};