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

    Solution:

     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         return countNodesRecur(root);
    14     }
    15 
    16     public int getLeftHeight(TreeNode cur){
    17         int h = 1;
    18         while (cur.left!=null){
    19             cur = cur.left;
    20             h++;
    21         }
    22         return h;
    23     }
    24 
    25     public int countNodesRecur(TreeNode root){
    26         int h = getLeftHeight(root);
    27         if (h==1) return 1;
    28 
    29         if (root.right==null) return 2;
    30         int rh = getLeftHeight(root.right);
    31 
    32         if (rh==h-1){
    33             // root.left is a complete tree with height h-1
    34             return (1 << rh) -1 + 1 + countNodesRecur(root.right);
    35         } else {
    36             // root.right is a complete tree with height h-2
    37             return (1 << rh) - 1 + 1 + countNodesRecur(root.left);
    38         }
    39     }
    40 }
  • 相关阅读:
    PB中的Grid视图
    MVC加jquery的无刷新列表分页摘要
    Quartz.Net 1.30的一些设置说明
    将Excel的数据库字典导到PDM中
    HubbleDotNet使用备忘
    EntLib5.0 日志应用程序块(logging) 使用与配置
    生成随机密码
    网站整合QQ登录
    PB代码参考段
    SQL查询之 Pivot 详解
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5795172.html
Copyright © 2011-2022 走看看