美文网首页
LeetCode:98. 验证二叉搜索树中序遍历实现

LeetCode:98. 验证二叉搜索树中序遍历实现

作者: 天降小纸箱 | 来源:发表于2021-01-06 23:39 被阅读0次

给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/validate-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

实现思路:非递归中序遍历二叉搜索树,用一个变量暂存最小值,中序遍历时若后面的比前面的小,则未非二叉搜索树

实现代码:

public static boolean isValidBST(TreeNode root) {
        long min = Long.MIN_VALUE; // 此处用long是用来避免同是Integer的最小值
        Stack<TreeNode> stack = new Stack<>();
        while (!stack.isEmpty() || root != null) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if (root.val <= min) {
                return false;
            }
            min = root.val;
            root = root.right;
        }
        return true;
    }

递归实现计算二叉树高度

public static int maxDepth(TreeNode root) {
        if (root == null) return 0;
        int l = maxDepth(root.left);
        int r = maxDepth(root.right);
        return l > r ? l + 1 : r + 1;
    }

相关文章

网友评论

      本文标题:LeetCode:98. 验证二叉搜索树中序遍历实现

      本文链接:https://www.haomeiwen.com/subject/nuraoktx.html