zoukankan      html  css  js  c++  java
  • 【LeetCode】222. Count Complete Tree Nodes

    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.

    完全二叉树相比普通二叉树,在计数时候一个trick在于,当最后一层是满的(最左深度等于最右深度),

    就不需要通过遍历方式来计数,直接等于2^h - 1

    /**
     * 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) {
            if(root == NULL)
                return 0;
            TreeNode* l = root;
            int lefth = 0;
            while(l->left)
            {
                lefth ++;
                l = l->left;
            }
            TreeNode* r = root;
            int righth = 0;
            while(r->right)
            {
                righth ++;
                r = r->right;
            }
            if(lefth == righth)
                return pow(2.0, lefth+1) - 1;
            else
                return 1 + countNodes(root->left) + countNodes(root->right);
        }
    };

  • 相关阅读:
    第七周作业——用户体验
    第六周作业——Coder和Hacker的区别
    第五周作业——对lua的学习
    产品开发与竞争
    个人项目
    对代码规范的体悟
    第二周作业——浅谈产品同质化应对方法
    第一周作业
    第二次作业
    第一次作业
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4633843.html
Copyright © 2011-2022 走看看