• 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;
        }
    };
  • 相关阅读:
    使用正则表达式做代码匹配和替换
    python 简单日志框架 自定义logger
    UVa 221 Urban Elevations 城市正视图 离散化初步 无限化有限
    UVa 10562 Undraw the Trees 看图写树
    【如何学习Python课程】
    【linux端口号与PID的互相查询】
    supervisor基础一
    【logstash】安装配置

    markdown
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5417142.html
Copyright © 2020-2023  润新知