1317. 统计完全树节点数
给定一棵完全二叉树,计算它的节点数。
样例
样例1
输入: {1,2,3,4,5,6}
输出: 6
解释:
1
/ \
2 3
/ \ /
4 5 6
样例2
输入: {1,2,3,4,5,6,8}
输出: 7
解释:
1
/ \
2 3
/ \ /\
4 5 6 8
注意事项
在完全二叉树中,除了可能的最后一层之外,每层都被完全填充,并且最后一层中所有节点都尽可能地靠左。 最后一层h中,可能有1到2 ^ h个节点。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: root of complete binary tree
* @return: the number of nodes
*/
public int countNodes(TreeNode root) {
// write your code here
if (root==null)return 0;
return 1+countNodes(root.left)+countNodes(root.right);
}
}