題目:
https://leetcode.com/problems/count-complete-tree-nodes/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public: int leftH(TreeNode* root){ if(root==nullptr)return 0; return 1+leftH(root->left); } int rightH(TreeNode* root){ if(root==nullptr)return 0; return 1+rightH(root->right); }
int countNodes(TreeNode* root) { if(root==nullptr)return 0; int left=leftH(root); int right=rightH(root); if(left==right){ return (int)pow(2,left)-1; } return 1+countNodes(root->left)+countNodes(root->right); } };
|