leetcode_222 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.
思路1:
暴力解决,遍历树的所有节点,依次统计。
会超时,题目限定了该二叉树是完全二叉树,该种思路适用于所有二叉树。
思路2:
暴力解决无法测试通过,此时需要考虑完全二叉树的特点。
完全二叉树,至少有一课子树是完美二叉树,另一课子树至少是完全二叉树。
因此可以递归的计算。
判断完美二叉树:
最内侧的叶子结点和最外侧的叶子结点是否在同一层。
代码:
1 public static int countNodes(TreeNode root){ 2 if(root == null){ 3 return 0; 4 } 5 6 int hl = getLeft(root)+1; 7 int hr = getRight(root)+1; 8 9 if(hl == hr){ 10 int num = (2<<(hl-1))-1; 11 return num; 12 }else{ 13 return countNodes(root.left)+countNodes(root.right)+1; 14 } 15 } 16 17 public static int getRight(TreeNode root) { 18 int cou = 0; 19 TreeNode ptr = root; 20 while(ptr.right != null){ 21 cou++; 22 ptr = ptr.right; 23 } 24 return cou; 25 } 26 27 public static int getLeft(TreeNode root) { 28 int cou = 0; 29 TreeNode ptr = root; 30 while(ptr.left != null){ 31 cou++; 32 ptr = ptr.left; 33 } 34 return cou; 35 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)