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.

    思路:

    Full v.s. Complete Binary Trees

    According to wikipedia

    • A full binary tree (sometimes proper binary tree or 2-tree) is a tree in which every node other than the leaves has two children. ?
    • A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. ?

    Steps to solve this problem:
    1) get the height of left-most part
    2) get the height of right-most part
    3) when they are equal, the # of nodes = 2^h -1
    4) when they are not equal, recursively get # of nodes from left&right sub-trees

    count-complete-tree-nodes

    count-complete-tree-nodes-2

    Time complexity is O(h^2).

    代码:

     1 public int countNodes(TreeNode root) {
     2     if(root==null)
     3         return 0;
     4  
     5     int left = getLeftHeight(root)+1;    
     6     int right = getRightHeight(root)+1;
     7  
     8     if(left==right){
     9         return (2<<(left-1))-1;
    10     }else{
    11         return countNodes(root.left)+countNodes(root.right)+1;
    12     }
    13 }
    14  
    15 public int getLeftHeight(TreeNode n){
    16     if(n==null) return 0;
    17  
    18     int height=0;
    19     while(n.left!=null){
    20         height++;
    21         n = n.left;
    22     }
    23     return height;
    24 }
    25  
    26 public int getRightHeight(TreeNode n){
    27     if(n==null) return 0;
    28  
    29     int height=0;
    30     while(n.right!=null){
    31         height++;
    32         n = n.right;
    33     }
    34     return height;
    35 }

    reference:http://www.programcreek.com/2014/06/leetcode-count-complete-tree-nodes-java/

  • 相关阅读:
    Java反射【三、方法的反射】
    Java反射【二、Class类的使用】
    Java反射【一、概述】
    MySql学习笔记【四、数据相关操作】
    MySql学习笔记【三、表相关操作】
    MySql学习笔记【二、库相关操作】
    MySQL 表查询
    MySQL 表之间的关系
    MySQL 数据类型
    数据库概念 MySQL语法
  • 原文地址:https://www.cnblogs.com/hygeia/p/4772126.html
Copyright © 2011-2022 走看看