222. Count Complete Tree Nodes(Leetcode每日一題-2020.11.24)

Bryan要加油發表於2020-11-24

Problem

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

在這裡插入圖片描述

Solution

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int countNodes(TreeNode* root) {
        if(!root)
            return 0;
        TreeNode *l = root->left;
        TreeNode *r = root->right;

        int l_depth = 1;
        int r_depth = 1;
        while(l)
        {
            l = l->left;
            ++l_depth;
        }

        while(r)
        {
            r = r->right;
            ++r_depth;
        }

        if(l_depth == r_depth)
            return (1 << l_depth) - 1;
        
        return countNodes(root->left) + 1 + countNodes(root->right);

    }
};

相關文章