• LeetCode OJ 222. Count Complete Tree Nodes


    Total Accepted: 32628 Total Submissions: 129569 Difficulty: Medium

    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.

    如果用暴力递归来计算节点总数,那么会超时,时间复杂度是O(N)。由于我们求的是完全二叉树的节点数,如果用求普通二叉树的方法来解决肯定是不合适的。完全二叉树的一些特点可能成为我们解决该问题的思路:如果一个节点的左子树的深度和右子树的深度一样,那么以该节点为根节点的树的节点数为:h2-1。最好情况下的时间复杂度为O(h),其它情况的时间复杂度为O(h2)。代码如下:

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public int countNodes(TreeNode root) {  
    12         if(root==null) return 0;  
    13           
    14         int l = getLeft(root) + 1;  
    15         int r = getRight(root) + 1;  
    16           
    17         if(l==r) {  
    18             return (2<<(l-1)) - 1;  
    19         } else {  
    20             return countNodes(root.left) + countNodes(root.right) + 1;  
    21         }  
    22     }  
    23       
    24     private int getLeft(TreeNode root) {  
    25         int count = 0;  
    26         while(root.left!=null) {  
    27             root = root.left;  
    28             ++count;  
    29         }  
    30         return count;  
    31     }  
    32       
    33     private int getRight(TreeNode root) {  
    34         int count = 0;  
    35         while(root.right!=null) {  
    36             root = root.right;  
    37             ++count;  
    38         }  
    39         return count;  
    40     }  
    41 }
     
  • 相关阅读:
    使 Inno Setup 打包出的安装程序以管理员身份运行
    SQL SERVER 数据库被标记为“可疑”的解决办法
    SQL SERVER 查看数据库信息
    【转】如何正确地处理时间
    如何获取 XAML 控件的模板代码
    Asp.Net MVC 把PartialView、View转换成字符串
    表达式树在LINQ动态查询
    ASP.NET MVC5 实现分页查询
    WPF
    正则表达式定义
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5472735.html
Copyright © 2020-2023  润新知