給定完全二叉樹根節點,求節點總數。完全二叉樹:除最後一層外滿,最後一層靠左排列。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int getHeight(TreeNode* root) {
int h = 0;
while (root) { root = root->left; ++h; }
return h;
}
int countNodes(TreeNode* root) {
if (!root) return 0;
int lh = getHeight(root->left);
int rh = getHeight(root->right);
if (lh == rh) return (1 << lh) + countNodes(root->right);
else return (1 << rh) + countNodes(root->left);
}
};
O(log² n),空間 O(log n)(遞歸棧)。