首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Leetcode 222. Count Complete Tree Nodes

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://cloud.tencent.com/developer/article/1433674

文章作者:Tyan

博客:noahsnail.com | CSDN | 简书

1. Description

2. Solution

代码语言:javascript
复制
/**
 * 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;
        }
        int leftDepth = 0;
        int rightDepth = 0;
        TreeNode* left = root;
        TreeNode* right = root;
        while(left) {
            leftDepth++;
            left = left->left; 
        }
        while(right) {
            rightDepth++;
            right = right->right; 
        }
        if(leftDepth == rightDepth) {
            return pow(2, leftDepth) - 1;
        }
        else {
            return 1 + countNodes(root->left) + countNodes(root->right);
        }
    }
};

Reference

  1. https://leetcode.com/problems/count-complete-tree-nodes/description/
举报
领券