Java-LeetCode98. 验证二叉搜索树&958. 二叉树的完全性检验-中序遍历 | 递归 & 层次遍历

判断一棵二叉树是否为搜索二叉树和完全二叉树

http://www.nowcoder.com/questionTerminal/f31fc6d3caf24e7f8b4deb5cd9b5fa97

LeetCode98. 验证二叉搜索树

  • 算法
    • 1.递归
    • 2.重载一个函数,界定节点值的范围(lower, upper)
    • 3.递归判断左子树和右子树是否是二叉搜索树
public boolean isValidBST(TreeNode root) {
    return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
}

private boolean isValidBST(TreeNode root, long lower, long upper) {
    if (root == null) {
        return true;
    }
    if (root.val <= lower || root.val >= upper) {
        return false;
    }
    return isValidBST(root.left, lower, root.val) && isValidBST(root.right, root.val, upper);
}
public boolean isValidBST(TreeNode root) {
    ArrayList<Integer> list = new ArrayList<>(10);
    Stack<TreeNode> stack = new Stack<>();
    TreeNode curr = root;
    while (!stack.isEmpty() || curr != null) {
        if (curr != null) {
            stack.push(curr);
            curr = curr.left;
        } else {
            curr = stack.pop();
            list.add(curr.val);
            curr = curr.right;
        }
    }
    for (int i = 1; i < list.size(); i++) {
        if (list.get(i) <= list.get(i-1)) {
            return false;
        }
    }
    return true;
}
  • 算法
    • 1.层次遍历直至遇到第一个空节点
    • 2.完全二叉树在遇到空节点之后剩余的应当全是空节点
public boolean isCompleteTree(TreeNode root) {
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.offer(root);
    while (queue.peek() != null) {
        TreeNode node = queue.poll();
        queue.offer(node.left);
        queue.offer(node.right);
    }

    while (!queue.isEmpty() && queue.peek() == null) {
        queue.poll();
    }
    return queue.isEmpty();
}
全部评论
是我敲错了..赣
点赞 回复 分享
发布于 2021-04-04 18:37
大佬,你的代码只跑了80%,是哪有问题呢??我再检查看看
点赞 回复 分享
发布于 2021-04-04 18:33

相关推荐

评论
35
2
分享

创作者周榜

更多
牛客网
牛客企业服务