zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    C#设计模式——抽象工厂模式(原文转自:http://blog.jobbole.com/78059/)
    WebConfig配置文件详解(转载自逆心的博客)
    ASP.NET C# 日期 时间 年 月 日 时 分 秒 格式及转换(转自happymagic的专栏)
    ASP.NET RepeatLayout 属性
    牛顿迭代法
    汉诺塔(整理)
    游戏引擎---好牛(转)
    字符串相关面试题(整理)
    有关java调用批处理文件
    有关java 8
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5417142.html
Copyright © 2011-2022 走看看