Find Size - Binary Tree
We can find the size of a binary tree (i.e. the number of nodes in that binary tree) by adding 1 (for the root node), the size of the left subtree, and the size of the right subtree. Here's a possible implementation:
int size(Node *root) {
if (root == nullptr) return 0;
return 1 + size(root->left) + size(root->right);
}
Time complexity
The time complexity is O(n) (where n is the number of nodes in the tree) because that's the total work done when we combine the work done by each recursive call. See the video for more detail.
Space complexity
The space complexity is O(h) (where h is the height of the tree) because of the space taken by the call stack. See the video for more detail.