Given a complete binary tree, count the number of nodes.
Note:
<u style="box-sizing: border-box;">Definition of a complete binary tree from Wikipedia:</u>
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.
Example:
我的解法:
/**
* 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 countNodes(TreeNode* root) {
return (root==nullptr) ? 0:recurr(root);
}
int recurr(TreeNode* root) {
int left_num = (root->left==nullptr) ? 0:recurr(root->left);
int right_num = (root->right==nullptr) ? 0:recurr(root->right);
return 1+left_num+right_num;
}
};
Runtime: 40 ms, faster than 77.31% of C++ online submissions for Count Complete Tree Nodes.
Memory Usage: 31.4 MB, less than 84.20% of C++ online submissions for Count Complete Tree Nodes.
第一反应就是递归,但是发现速度并不是特别特别快,
递归的写法,看评论区:
class Solution {
public:
int countNodes(TreeNode* root) {
if (!root) return 0;
queue<TreeNode*> que;
que.push(root);
int c = 0;
while (!que.empty()) {
TreeNode* node = que.front();
que.pop();
c++;
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
return c;
}
};
但其实也是40ms, 不过用一个static的count variable还挺新奇的。
还有一行流
class Solution {
public:
int countNodes(TreeNode* root) {
return !root ? 0 : ((root->left ? countNodes(root->left) : 0) + (root->right ? countNodes(root->right) : 0) + 1);
}
};
确实没想到调用自己!
但号称100%结果runtime 44ms
网友评论