前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 0222 - Count Complete Tree Nodes

LeetCode 0222 - Count Complete Tree Nodes

作者头像
Reck Zhang
发布2021-08-11 12:14:45
2890
发布2021-08-11 12:14:45
举报
文章被收录于专栏:Reck ZhangReck Zhang

Count Complete Tree Nodes

Desicription

Given a complete binary tree, count the number of nodes.

Note:

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:

代码语言:javascript
复制
Input: 
    1
   / \
  2   3
 / \  /
4  5 6

Solution

代码语言:javascript
复制
class Solution {
public:
    int countNodes(TreeNode* root) {
        return countAll(root, -1, -1);
    }
    int countAll(TreeNode* root, int left_depth, int right_depth) {
        if(left_depth == -1) {
            left_depth = leftDepth(root);
        }
        if(right_depth == -1) {
            right_depth = rightDepth(root);
        }
        if(left_depth == right_depth) {
            return static_cast<int>(pow(2, left_depth) - 1);
        }
        return 1 + countAll(root->left, left_depth - 1, -1) + countAll(root->right, -1, right_depth - 1);
    }
    int leftDepth(TreeNode* root) {
        if(root == nullptr) {
            return 0;
        }
        return 1 + leftDepth(root->left);
    }
    int rightDepth(TreeNode* root) {
        if(root == nullptr) {
            return 0;
        }
        return 1 + rightDepth(root->right);
    }
};
本文参与?腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-07-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体同步曝光计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Count Complete Tree Nodes
    • Desicription
      • Solution
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
      http://www.vxiaotou.com