Total accepted:32628 Total submissions:129569 difficulty:medium
Given a complete binary tree, count the number of nodes.
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, was completely filled, and all nodes As far left as possible. It can has between 1 and 2h nodes inclusive at the last level H.
If the total count of nodes is returned with brute force, then the time-out will be exceeded, and the complexity is O (N). Since we are asking for the total number of nodes in a binary tree, it is not appropriate to use the common binary tree method to solve the problem. Some of the features of a complete binary tree may be our idea of solving this problem: if the depth of the left subtree of a node is the same as the depth of the right subtree, then the number of nodes in the tree with that node as the root node is: h2-1. In the best case, the time complexity is O (h), and the time complexity of other cases is O (H2). The code is as follows:
1 /**2 * Definition for a binary tree node.3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8 * }9 */Ten Public classSolution { One Public intcountnodes (TreeNode root) { A if(root==NULL)return0; - - intL = getLeft (root) + 1; the intR = getRight (root) + 1; - - if(l==r) { - return(2<< (L-1))-1; +}Else { - returnCountnodes (Root.left) + countnodes (root.right) + 1; + } A } at - Private intgetLeft (TreeNode root) { - intCount = 0; - while(root.left!=NULL) { -Root =Root.left; -++count; in } - returncount; to } + - Private intgetRight (TreeNode root) { the intCount = 0; * while(root.right!=NULL) { $Root =Root.right; Panax Notoginseng++count; - } the returncount; + } A}
Leetcode OJ 222. Count Complete Tree Nodes