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.
数二叉树的节点数首先肯定是可以用暴力揭发去解问题的,但是这样总是会timeout:
1 class Solution { 2 public: 3 int countNodes(TreeNode* root) { 4 if(!root) return 0; 5 total++; 6 countNodes(root->left); 7 countNodes(root->right); 8 return total; 9 } 10 private: 11 int total; 12 };
其他的办法就是对完全二叉树而言,其一直向左走和一直向右边、走只可能是相同的或者相差1,如果相同那么起节点个数就是2^h - 1否曾再递归的加上左右节点的和就可以了。
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int countNodes(TreeNode* root) { 13 if(!root) return 0; 14 TreeNode * leftNode = root; 15 TreeNode * rightNode = root; 16 int left = 0; 17 int right = 0; 18 while(leftNode->left){ 19 left++; 20 leftNode=leftNode->left; 21 } 22 while(rightNode->right){ 23 right++; 24 rightNode = rightNode->right; 25 } 26 if(left == right) return (1 << (left + 1)) - 1; 27 else return 1 + countNodes(root->left) + countNodes(root->right); 28 } 29 };
写的比较乱哈 ,凑合着看看把。
时间: 2024-10-12 06:31:17