Table of contents
222. Number of nodes in a complete binary tree - LeetCode
Given the root node of a complete binary tree
root
, find the number of nodes in the tree.The definition of a complete binary tree is as follows: In a complete binary tree, except for the bottom node, which may not be filled, the number of nodes in each layer reaches the maximum, and the nodes in the bottom layer are concentrated in the leftmost positions of the layer. If the lowest layer is the th
h
layer, then the layer contains1~ 2h
nodes.Example 1:
Input: root = [1,2,3,4,5,6] Output: 6Example 2:
Input: root = [] Output: 0Example 3:
Input: root = [1] Output: 1hint:
- The range of the number of nodes in the tree is
[0, 5 * 104]
0 <= Node.val <= 5 * 104
- The question data ensures that the input tree is a complete binary tree
Code:
/** * 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 countNodes(root.left)+countNodes(root.right)+1; } }
operation result: