一、题目描述
题目链接:https://leetcode-cn.com/problems/count-complete-tree-nodes/
二、题目分析
真的是妙蛙种子吃着妙脆角进了妙妙屋,妙到家了。
这道题结合完全二叉树的性质,再想象一下树长什么样子,再结合代码进行体会,感觉自己的水平说不清楚。当是自己的笔记吧
三、代码
public int countNodes(TreeNode root) {
if (root == null) return 0;
int left = countNodesHelper(root.left);
int right = countNodesHelper(root.right);
if (left == right) {
return countNodes(root.right) + (1 << left);
} else {
return countNodes(root.left) + (1 << right);
}
}
private int countNodesHelper(TreeNode root) {
int count = 0;
while (root != null) {
count += 1;
root = root.left;
}
return count;
}