The number of nodes of the complete binary tree

It gives a complete binary tree, obtains the number of nodes of the tree.

Description:

Complete binary tree is defined as follows: in the binary tree, except the bottom node may not be filled, the remaining maximum number of nodes each, and the bottom layer of nodes are concentrated in a plurality of layers of the leftmost position. If the bottom of the h layer, the layer comprising the nodes 1 ~ 2h.

Example:

Input:
1
/
23
/ \ /
456

Output: 6

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int countNodes(TreeNode root) {
        if(root==null){
            return 0;
        }
        return countNodes(root.left)+countNodes(root.right)+1;
    }
}
Published 71 original articles · won praise 3 · Views 1030

Guess you like

Origin blog.csdn.net/qq_44262984/article/details/105165476