Count Complete Tree Nodes (Medium?)

Problem: https://leetcode.com/problems/count-complete-tree-nodes/description/

Given a complete binary tree, count the number of nodes.
Note:
Definition of a complete binary tree from Wikipedia:
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:
Input: 
    1
   / \
  2   3
 / \  /
4  5 6

Output: 6

Not sure why this was flagged as medium... code is below, works fast.


public class Solution {
    public int CountNodes(TreeNode root) {
        if(root==null) return 0;
        return 1 +CountNodes(root.left)+CountNodes(root.right);
    }
}

Comments

  1. Super concise, although this solution does not take advantage of the fact that it's a complete tree. In particular parts of the tree that have the same left and right path lengths, we can count all nodes using a formula - path_length ** 2 - 1. Using this makes the implementation somewhat more cumbersome:

    class Solution {
    public:
    int countNodes(TreeNode* root) {
    if (root == nullptr) return 0;
    int left_height = 0;
    int right_height = 0;
    for (auto temp = root; temp != nullptr; temp = temp->left) left_height += 1;
    for (auto temp = root; temp != nullptr; temp = temp->right) right_height += 1;
    if (left_height == right_height) return pow(2, left_height) - 1;
    return 1 + countNodes(root->left) + countNodes(root->right);
    }
    };

    https://gist.github.com/ttsugriy/cdfa31a4f71508cab769bcb1b2b389fe

    ReplyDelete

Post a Comment

Popular posts from this blog

Count Binary Substrings

Count Vowels Permutation: Standard DP

Maximum Number of Balloons