Given the root of a complete binary tree, return the number of the nodes in the tree.
According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, 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.
Design an algorithm that runs in less than O(n) time complexity.
#이진트리 #preorder #재귀
모든 노드의 수를 세어야 하므로 모든 노드를 순회하는 preorder 알고리즘으로 해결하였다. inorder, postorder로도 가능하다.
/**
* 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 answer = 0;
void preorder(TreeNode* node) {
if(node == NULL) return;
answer++;
if(node->left != NULL) preorder(node->left);
if(node->right != NULL) preorder(node->right);
}
int countNodes(TreeNode* root) {
preorder(root);
return answer;
}
};
Runtime: 77 ms, faster than 18.19% of C++ online submissions for Count Complete Tree Nodes.
Memory Usage: 30.9 MB, less than 63.27% of C++ online submissions for Count Complete Tree Nodes.