标签:
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, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
直接遍历一遍会超时,代码如下:
1 class Solution { 2 public: 3 int countNodes(TreeNode* root) { 4 int count = 0; 5 queue<TreeNode *> temp; 6 if (root == NULL) 7 { 8 return 0; 9 } 10 temp.push(root); 11 while (!temp.empty()) 12 { 13 TreeNode * Node = temp.front(); 14 count++; 15 temp.pop(); 16 17 if (Node->left != NULL) 18 { 19 temp.push(Node->left); 20 } 21 if (Node->right != NULL) 22 { 23 temp.push(Node->right); 24 } 25 } 26 return count; 27 } 28 };
1 class Solution { 2 public: 3 int countNodes(TreeNode* root) { 4 int leftnum = 0; 5 int rightnum = 0; 6 TreeNode * ptr = root; 7 8 if (root == NULL) 9 { 10 return 0; 11 } 12 13 while (1) 14 { 15 ptr = ptr->left; 16 if (ptr != NULL) 17 { 18 ++leftnum; 19 } 20 else 21 { 22 break; 23 } 24 } 25 ptr = root; 26 while (1) 27 { 28 ptr = ptr->right; 29 if (ptr != NULL) 30 { 31 ++rightnum; 32 } 33 else 34 { 35 break; 36 } 37 } 38 if (leftnum == 0 && rightnum == 0) 39 { 40 return 1; 41 } 42 if (leftnum == rightnum) 43 { 44 return pow(2, leftnum + 1) - 1; 45 } 46 return 1 + countNodes(root->left) + countNodes(root->right); 47 } 48 };
222. Count Complete Tree Nodes
标签:
原文地址:http://www.cnblogs.com/hhboboy/p/5768331.html