Count Complete Tree Nodes
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 2Hnodes inclusive at the last level H.
Problem Solving Ideas:
Test instructions is the number of nodes that compute a complete binary tree. A complete binary tree is a node that has two children except the bottommost node, and the bottom node is as far as possible on the left two fork tree.
Solution 1: Violence all over the calendar, with a recursive traversal. The time complexity of this method is O (N), which results in a timeout error.
/** * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (NULL) , right (NULL) {}}; */class Solution {public: int countnodes (treenode* root) { if (root==null) { return 0; } Return 1 + countnodes (root->left) + countnodes (root->right); }};
Solution 2: Notice that for a complete binary tree, any node, with its left/right child as the root node of the child tree height difference of one, and at most only one subtree is not full two fork tree (except for the leaf node, all nodes have two child nodes, and the leaf node on the same layer). Calculate the leftmost and most right height of a node root LH, RH, if LH==RH, then the number of child tree nodes as root node is 2^ (LH)-1, otherwise the number of nodes =1+ to root->left as the root node of the number of child tree nodes + root-> Right is the number of child tree nodes of the root node
Note A little trick, 2^n can be obtained by shifting.
The time complexity of this method is O (h^2), because the most time-consuming operation is to calculate the height of a tree with a node as the root node, and the worst-case scan Count is (1+2+...+h).
/** * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (NULL) , right (NULL) {}}; */class Solution {public: int countnodes (treenode* root) { if (root==null) { return 0; } int lefth = getleftheight (root); int righth = getrightheight (root); if (lefth = = righth) { return ((1<<lefth)-1); } Return 1 + countnodes (root->left) + countnodes (root->right); } int getleftheight (treenode* root) { int h = 0; while (root!=null) { h++; root = root->left; } return h; } int getrightheight (treenode* root) { int h = 0; while (root!=null) { h++; root = root->right; } return h; }};
[Leetcode] Count complete Tree Nodes