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;
        }
    };
  • 相关阅读:
    Web前端工程师技能列表
    CSS框架的相关汇总(CSS Frameworks)
    一个有趣的发现
    (转丁学)Firefox2的一个bug和脑子进了水的IE
    深入语义:列表Tag(ul/ol)和表格Tag(table)的抉择
    css命名简单框架
    腾讯的三栏布局考题
    土豆网前端概况
    伪绝对定位(译)
    右下角浮动广告代码DEMO
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5417142.html
Copyright © 2011-2022 走看看