LeetCode-222. 完全二叉树的节点个数-Java-medium

题目链接

法一(普通二叉树DFS)
    /**
     * 法一(普通二叉树DFS)
     * 时间复杂度:O(n)
     * 空间复杂度:O(logn)
     *
     * @param root
     * @return
     */
    public int countNodes(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return countNodes(root.left) + countNodes(root.right) + 1;
    }
法二(普通二叉树BFS)
    /**
     * 法二(普通二叉树BFS)
     * 时间复杂度:O(n)
     * 空间复杂度:O(n)
     *
     * @param root
     * @return
     */
    public int countNodes_2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int cnt = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            cnt += size;
            while (size-- > 0) {
                TreeNode cur = queue.poll();
                if (cur.left != null) queue.offer(cur.left);
                if (cur.right != null) queue.offer(cur.right);
            }
        }
        return cnt;
    }
法三(利用完全二叉树性质DFS)
    /**
     * 法三(利用完全二叉树性质DFS)
     * 1. 完全二叉树只有两种情况
     *(1)完全二叉树是满二叉树
     *    满二叉树的结点数为 2^depth - 1,注意这里根节点深度为1
     *(2)完全二叉树最后一层叶子节点没有满
     *    分别递归左孩子,和右孩子,递归到某一深度一定会有左孩子或者右孩子为满二叉树,然后依然可以按照情况1来计算
     * 2. 复杂度
     * 时间复杂度:O(logn * logn)
     * 空间复杂度:O(logn)
     *
     * @param root
     * @return
     */
    public int countNodes_3(TreeNode root) {
        if (root == null) {
            return 0;
        }
        TreeNode left = root.left, right = root.right;
        int leftDepth = 0, rightDepth = 0; // 初始为0
        while (left != null) { // 求左子树深度
            left = left.left;
            leftDepth++;
        }
        while (right != null) { // 求右子树深度
            right = right.right;
            rightDepth++;
        }
        if (leftDepth == rightDepth) {   // 以root为根的完全二叉树是满二叉树
            return (2 << leftDepth) - 1; // 注意(2<<1) 相当于2^2,因此leftDepth初始为0
        }
        return countNodes(root.left) + countNodes(root.right) + 1;
    }
本地测试
        /**
         * 222. 完全二叉树的节点个数
         */
        lay.showTitle(222);
        Solution222 sol222 = new Solution222();
        List<Integer> arr222 = Arrays.asList(7, 3, 15, null, null, 9, 20);
        TreeNode root222 = treeOpt.createTreeByLayerOrder(arr222);
        treeOpt.layerOrder(root222);
        System.out.println(sol222.countNodes(root222));
        System.out.println(sol222.countNodes_2(root222));
        System.out.println(sol222.countNodes_3(root222));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值