zoukankan      html  css  js  c++  java
  • 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.

    FIND A MORE EFFICIENT CODE!!!

    Analyse: 

    1. do level traversal, count and add up the node(s) at each level.

        NA:  TIME LIMIT EXCEEDED

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int countNodes(TreeNode* root) {
    13         if(!root) return 0;
    14         queue<TreeNode* > qu;
    15         qu.push(root);
    16         int result = 0;
    17         while(!qu.empty()){
    18             int n = qu.size();
    19             result += n;
    20             while(n--){
    21                 TreeNode* temp = qu.front();
    22                 qu.pop();
    23                 if(temp->left) qu.push(temp->left);
    24                 if(temp->right) qu.push(temp->right);
    25             }
    26         }
    27         return result;
    28     }
    29 };
    View Code

    2. Continuously judge whether the left level and right level are equal. If they are equal, return 2^level - 1; If not, compute 1 + nodes(left) + nodes(right).

        Runtime: 164ms.

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int countNodes(TreeNode* root) {
    13         if(!root) return 0;
    14         
    15         int leftLevel = 1, rightLevel = 1;
    16         TreeNode* temp = root->left;
    17         while(temp){
    18             leftLevel++;
    19             temp = temp->left;
    20         }
    21         temp = root->right;
    22         while(temp){
    23             rightLevel++;
    24             temp = temp->right;
    25         }
    26         
    27         if(leftLevel == rightLevel) 
    28             return (1 << leftLevel) - 1;
    29         
    30         return 1 + countNodes(root->left) + countNodes(root->right);
    31     }
    32 };
  • 相关阅读:
    简单的测试用例计划放法
    黑盒测试用例设计方法-等价类划分
    Redis净化板
    爬虫部署与Django
    怎样实现前端的优化
    关于Apache简介笔记
    yield生成器的经典案例
    石头剪刀布
    函数内是否可以修改传递进来的列表
    不定长参数的传递
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4698816.html
Copyright © 2011-2022 走看看