leetcode--Count Complete Tree Nodes

来源:互联网 发布:unity3d guitexture 编辑:程序博客网 时间:2024/06/04 18:16

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.


题意:给定一棵完全二叉树,计算节点数目。

分类:二叉树


解法1:完全二叉树的定义是,除最后一层外,每一层上的节点数均达到最大值;在最后一层上只缺少右边的若干结点。

完全二叉树的一个特殊例子是满二叉树。

如果一棵树是满二叉树,那么我们可以用公式2^k-1计算它的节点数目。

如果不是满二叉树,我们要分别计算左子树和右子树,这是一个递归过程,最好左右子树和+1,为结果

根据上面的说法,我们可以先通过查找最左边节点的个数,最右边节点的个数

如果这两个数目相同,就是满二叉树,可以通过公式直接返回

如果不同,则递归分别计算左右子树的数目

[java] view plain copy
  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==nullreturn 0;  
  13.         int left = getLeft(root.left)+1;  
  14.         int right = getRight(root.right)+1;  
  15.         if(left==right){//如果左右相等,就是满二叉树  
  16.             return (2<<(left-1))-1;    
  17.         }else{//如果左右不等,分别递归计算  
  18.             return countNodes(root.left)+countNodes(root.right)+1;  
  19.         }  
  20.     }  
  21.       
  22.     /** 
  23.      * 获得最左边节点的数目  
  24.      */  
  25.     int getLeft(TreeNode root){  
  26.         int left = 0;  
  27.         while(root!=null){  
  28.             left++;  
  29.             root = root.left;  
  30.         }  
  31.         return left;  
  32.     }  
  33.       
  34.     /**  
  35.      * 获得最右边节点的数目  
  36.     int getRight(TreeNode root){  
  37.         int right = 0;  
  38.         while(root!=null){  
  39.             right++;  
  40.             root = root.right;  
  41.         }  
  42.         return right;  
  43.     }  
  44. }  

原文链接http://blog.csdn.net/crazy__chen/article/details/47189559

原创粉丝点击