题解 | #判断是不是完全二叉树#

判断是不是完全二叉树

https://www.nowcoder.com/practice/8daa4dff9e36409abba2adbe413d6fae?tpId=295&tqId=2299105&ru=/exam/oj&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Foj

递归方式实现,完全二叉树满足以下条件

  1. 0 <= 左子树深度 - 右子树深度 <= 1
  2. 左子树为空,右子树一定为空
  3. 左右子树都存在的情况下,左子树的右子树为空,则右子树的左子树也一定为空
/**
 * 递归方式实现
 */
public static boolean isCompleteTreeByDfs(TreeNode root) {
    if (root == null) return true;
    if (root.left == null && root.right != null)
        return false;
    if (root.left != null && root.right != null) {
        if (root.left.right == null && root.right.left != null)
            return false;
    }
    return isCompleteTreeByDfs(root.left) && isCompleteTreeByDfs(root.right);
}

public static int maxDepthByDfs (TreeNode root) {
    return root == null ? 0 : Math.max(maxDepthByDfs(root.left),
                                       maxDepthByDfs(root.right)) + 1;
}

时间复杂度 O(n),空间复杂度 O(树的高度)

全部评论

相关推荐

深夜书店vv:腾讯是这样的,去年很多走廊都加桌子当工区
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务