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 }
  • 相关阅读:
    园 首页 新随笔 联系 管理 订阅 订阅 RTSP协议转换RTMP直播协议
    sequence diagram
    Model Binding
    asp.net mvc
    系统日志和异常的处理①
    随机森林之oob error 估计
    Extjs相关知识点梳理
    Extjs报错处理
    webbrowser在html中写入内容并添加js
    tcpdump一个命令的剖析
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5795172.html
Copyright © 2011-2022 走看看