• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ArgenBarbie
博客园    首页    新随笔    联系   管理    订阅  订阅
222. Count Complete Tree Nodes -- 求完全二叉树节点个数

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

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.

1. 递归

//return -1 if it is not.
int isCompleteTree(TreeNode* root) {
    if (!root) return 0;

    int cnt = 1;
    TreeNode *left = root, *right = root;
    for(; left && right; left=left->left, right=right->right) {
        cnt *= 2;
    }
      
    if (left!=NULL || right!=NULL) {
        return -1;
    }
    return cnt-1;
}

int countNodes(TreeNode* root) {
    int cnt = isCompleteTree(root);
    if (cnt != -1) return cnt;
    int leftCnt = countNodes(root->left);
    int rightCnt = countNodes(root->right);
    return leftCnt + rightCnt + 1;
}

 

2. 非递归

/**
 * 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) {
        int ans = 0, lh = 0, rh = 0;
        TreeNode *p = root;
        while(p)
        {
            //先求p的左右子树的最大深度。若相等,则p加左子树节点个数为1<<lh,再求右子树;若不等,则p加右子树节点个数为1<<rh,再求左子树。
            if(!lh) //若lh不为0,说明lh由之前的lh--得到,是已知的。
            {
                for(TreeNode *t = p->left; t; t = t->left)
                    lh++;
            }
            for(TreeNode *t = p->right; t; t = t->left)
                rh++;
            if(lh == rh)
            {
                ans += 1 << lh;
                p = p->right;
            }
            else
            {
                ans += 1 << rh;
                p = p->left;
            }
            lh--;
            rh = 0;
        }
        return ans;
    }
};

 

posted on 2016-04-21 15:30  ArgenBarbie  阅读(158)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3