222. Count Complete Tree Nodes(Leetcode每日一题-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);

    }
};
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 程序猿惹谁了 设计师:上身试试 返回首页