LeetCode 222. Count Complete Tree Nodes

本文介绍了一种计算完全二叉树节点数量的方法。利用递归的方式,通过比较左右子树的高度确定是否为满二叉树,并据此返回节点数量。此方法的时间复杂度为O(h²),空间复杂度为O(h)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接在这里:https://leetcode.com/problems/count-complete-tree-nodes/

题目:

Given a complete binary tree, count the number of nodes.

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. 

题解:

Complete Tree的定义是左右深度差不大于1. 

递归调用函数,终止条件两个,一个是root == null, return 0. 另一个是左右高度相同说明是满树, return 2^height-1.

若是左右高度不同,递归调用求 左子树包含Node数 + 右子树包含Node数 + 1(自身).

 

Note:1. 用Math.pow(), 注意arguments 和 return type 都是double, 此处会TLE.

2. 用<<来完成幂运算,但注意<<的precedence比+,-还要低,需要加括号.

 

Time Complexity: O(h^2). worst case对于每一层都要求一遍当前点到leaf得深度.

假设只有最底层多了一个TreeNode 那么计算height就需要每层计算一遍h + (h-1) + (h-2) + ... + 1 = O(h^2).

Space: O(h), stack space.

AC  Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public int countNodes(TreeNode root) {
12         if(root == null){
13             return 0;
14         }
15         TreeNode p = root;
16         TreeNode q = root;
17         int leftDepth = 0;
18         int rightDepth = 0;
19         while(p!=null){
20             leftDepth++;
21             p = p.left;
22         }
23         while(q!=null){
24             rightDepth++;
25             q = q.right;
26         }
27         
28         if(leftDepth == rightDepth){
29             return (1<<leftDepth) - 1;
30         }else{
31             return countNodes(root.left) + 1 + countNodes(root.right);
32         }
33     }
34 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4824980.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值