leetcode 222 完全二叉树的节点个数
题目链接
222. 完全二叉树的节点个数 - 力扣(LeetCode)
做题思路
这道题目可以递归或者迭代或者层序遍历的方法将每个节点遍历一边得出。但题目中指定为完全二叉树。因此,我们只需要求是不是满二叉树(最左边节点深度等于最右边节点深度)。若相同用公式求出,若不同,看其左子树或者右子树是不是。叶子结点一定是满二叉树。
解决方法
class Solution {
public int countNodes(TreeNode root) {
int count = 0;
TreeNode node = root;
if (root == null) return count;
TreeNode left = node.left;
TreeNode right = node.right;
int leftDeepth = 1;
int rightDeepth = 1;
while (left != null) {
left = left.left;
leftDeepth++;
}
while (right != null) {
right = right.right;
rightDeepth++;
}
if (leftDeepth == rightDeepth) {
count = (int) Math.pow(2, leftDeepth) - 1;
return count;
}
return countNodes(node.left) + countNodes(node.right) + 1;
}
}