zoukankan      html  css  js  c++  java
  • 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 }
     
  • 相关阅读:
    Git引用
    如何查看Git对象
    Git是如何存储对象的
    图形化的Git
    git中找回丢失的对象
    Git的Patch功能
    ES查看配置和查看全部配置
    增删改查
    Elasticsearch增、删、改、查操作深入详解
    ES博客链接
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5472735.html
Copyright © 2011-2022 走看看