关于网站集约化建设的意见,免费企业网站建设要求,上海健康证查询网址,eclipse做网站力扣labuladong一刷day40天计算完全二叉树节点数
一、222. 完全二叉树的节点个数
题目链接#xff1a;https://leetcode.cn/problems/count-complete-tree-nodes/ 思路#xff1a;计算完全二叉树直接全遍历的话很浪费时间#xff0c;但是可以利用完全二叉树的特性来解题https://leetcode.cn/problems/count-complete-tree-nodes/ 思路计算完全二叉树直接全遍历的话很浪费时间但是可以利用完全二叉树的特性来解题 每到一个节点我们就计算它的left node.left深度和rightnode.right的深度如果这两个深度想等总节点的个数就是2的h次方-1如果不相等那就把当前节点计数然后递归左右子树执行上面的每次左右子树都会有一个可以大化小小化无。
class Solution {public int countNodes(TreeNode root) {if (root null) return 0;TreeNode l root, r root;int a 0, b 0;while (l ! null) {l l.left;a;}while (r ! null) {r r.right;b;}if (a b) {return (int)Math.pow(2, a) - 1;}return 1 countNodes(root.left) countNodes(root.right);}
}