代码随想录Day22
LeetCode222. 完全二叉树的节点个数
给出一个完全二叉树,求出该树的节点个数。
示例 1:
- 输入:root = [1,2,3,4,5,6]
- 输出:6
示例 2:
- 输入:root = []
- 输出:0
示例 3:
- 输入:root = [1]
- 输出:1
提示:
- 树中节点的数目范围是[0, 5 * 10^4]
- 0 <= Node.val <= 5 * 10^4
- 题目数据保证输入的树是 完全二叉树
思路:
首先是完全二叉树的定义
思路:题目明确表明是一颗完全二叉树。我们可以根据公式求满二叉树的节点个数。
接下来,只要判断完全二叉树的左右子树是否是满二叉树,然后每一层返回深度就可以了。
对于不是满二叉树的情况再进行单独的处理。
class Solution { // 通用递归解法 public int countNodes(TreeNode root) { if(root == null) { return 0; } return countNodes(root.left) + countNodes(root.right) + 1; } } class Solution { // 迭代法 public int countNodes(TreeNode root) { if (root == null) return 0; Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); int result = 0; while (!queue.isEmpty()) { int size = queue.size(); while (size -- > 0) { TreeNode cur = queue.poll(); result++; if (cur.left != null) queue.offer(cur.left); if (cur.right != null) queue.offer(cur.right); } } return result; } } class Solution { /** * 针对完全二叉树的解法 * * 满二叉树的结点数为:2^depth - 1 */ public int countNodes(TreeNode root) { if(root == null) { return 0; } int leftDepth = getDepth(root.left); int rightDepth = getDepth(root.right); if (leftDepth == rightDepth) {// 左子树是满二叉树 // 2^leftDepth其实是 (2^leftDepth - 1) + 1 ,左子树 + 根结点 return (1 << leftDepth) + countNodes(root.right); } else {// 右子树是满二叉树 return (1 << rightDepth) + countNodes(root.left); } } private int getDepth(TreeNode root) { int depth = 0; while (root != null) { root = root.left; depth++; } return depth; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
· 零经验选手,Compose 一天开发一款小游戏!