[LeetCode] 98. Validate Binary Search Tree(是否是二叉搜索树) ☆☆☆

描述

解析

二叉搜素树,其实就是节点n的左孩子所在的树,每个节点都小于节点n。

节点n的右孩子所在的树,每个节点都大于节点n。

定义子树的最大最小值

比如:左孩子要小于父节点;左孩子n的右孩子要大于n的父节点。以此类推。

中序遍历

中序遍历时,输出的值,和前一个值比较,如果大,就失败。

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
public boolean isValidBST(TreeNode root) { if (null == root) { return true; } return isValidBSTHelper(root, null, null); } public boolean isValidBSTHelper(TreeNode root, Integer min, Integer max) { if (min != null && root.val <= min) { return false; } if (max != null && root.val >= max) { return false; } boolean left = root.left != null ? isValidBSTHelper(root.left, min, root.val) : true; if (left) { return root.right != null ? isValidBSTHelper(root.right, root.val, max) : true; } else { return false; } } }
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    Stack<TreeNode> stack = new Stack<>();
    //中序遍历
    public boolean isValidBST(TreeNode root) {
        if (null == root) {
            return true;
        }
        boolean flag = isValidBST(root.left);
        if (!flag) {
            return false;
        }
        TreeNode preNode = null;
        if (!stack.isEmpty()) {
            preNode = stack.peek();
        }
        if (null != preNode && root.val <= preNode.val) {
            return false;
        }
        stack.push(root);
        flag = isValidBST(root.right);
        if (!flag) {
            return false;
        }
        return true;
    }
}

当然还可以非递归中序遍历,存储节点的话,可以存2个就行。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isValidBST(TreeNode root) {
        if (root == null)
            return true;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode pre = null;
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if (pre != null && root.val <= pre.val)
                return false;
            pre = root;
            root = root.right;
        }
        return true;
    }
}

猜你喜欢

转载自www.cnblogs.com/fanguangdexiaoyuer/p/10604931.html
今日推荐