98. 验证二叉搜索树

98. 验证二叉搜索树
利用性质:二叉搜索树的中序遍历,是有顺序的

通过中序遍历,找到最小的节点。并以他为前驱节点,逐个向后遍历。判断后续节点和前驱节点的大小,同时更新前驱节点。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public Integer val = null;

    public boolean ans = true;

    public boolean isValidBST(TreeNode root) {
        dfs(root); 
        return ans;
    }
    public void dfs(TreeNode cur) {
        if (ans == false) return;
        if (cur == null) return;
        dfs(cur.left);
        if (val == null) {
            val = cur.val;
        }else {
            if (cur.val <= val) ans = false;
            else {
                val = cur.val;
            }
        }
        dfs(cur.right);
    }
}

你可能感兴趣的:(深度优先,算法)