zoukankan      html  css  js  c++  java
  • LeetCode222——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 2hnodes inclusive at the last level h.

    实现:
    class Solution {
    public:
        int getHeight(TreeNode* root) {
            int h = 0;
            while (root) {
                root = root->left;
                h++;
            }
            return h;
        }
        int countNodes(TreeNode* root) {
            if (!root) return 0;
            int lh = getHeight(root->left);
            int rh = getHeight(root->right);
            
            if (lh == rh) 
                return pow(2, lh) + countNodes(root->right);
            return pow(2, rh) + countNodes(root->left);
        }
    };

  • 相关阅读:
    servlet异步处理机制
    分析logfilter+session
    java web后台工作原理
    xml的作用
    本学期学习目标 企业级运用和互联网运用的区别
    JAVA EE 思维导图
    第六周
    第五周
    第四周作业
    javaee第三周
  • 原文地址:https://www.cnblogs.com/tlnshuju/p/7189925.html
Copyright © 2011-2022 走看看