https://leetcode.cn/problems/count-complete-tree-nodes/
题目要求
给出一个完全二叉树,求出该树的节点个数。
遍历
public int countNodes(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int res = 0;
while (!queue.isEmpty()) {
int n = queue.size();
for (int i = 0; i < n && !queue.isEmpty(); i++) {
TreeNode cur = queue.poll();
res++;
if (cur.left != null) queue.offer(cur.left);
if (cur.right != null) queue.offer(cur.right);
}
}
return res;
}
递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int countNodes(TreeNode root) {
if (root == null) return 0;
return 1 + countNodes(root.left) + countNodes(root.right);
}
}
思路
- 遍历最容易想到,但是方法的效率不高;
- 递归法和求二叉树的深度写法类似,只是要记录节点的数量;