数据结构2 二叉树的高度和宽度

宽度:节点的叶子数
深度:节点的层数

算法上有所谓的"宽度优先算法"和"深度优先算法"

 

二叉树的宽度定义为具有最多结点数的层中包含的结点数。

 

 

 

比如上图中,

第1层有1个节点, 

第2层有2个节点, 

第3层有4个节点, 

第4层有1个节点,

可知,第3层的结点数最多

所以这棵二叉树的宽度就是4

 

定义一个节点类

class TreeNode {
    char val;
    TreeNode left = null;
    TreeNode right = null;

    TreeNode(char _val) {
        this.val = _val;
    }
}

 

1求高度

这个可以使用递归,分别求出左子树的深度、右子树的深度,两个深度的较大值+1即可。

int  getHeight(TreeNode root)
{
    if(root==null)
       return 0;  
   else{
       int left=getHeight(root.left);
       int right=getHeight(root.right);
       return 1+Math.max(left,right);
         }
}

 2求宽度

 使用队列,层次遍历二叉树。在上一层遍历完成后,下一层的所有节点已经放到队列中,此时队列中的元素个数就是下一层的宽度。以此类推,依次遍历下一层即可求出二叉树的最大宽度。

public int getWeight(TreeNode root)
{
     if(root==null)
         return 1;

   Queue <TreeNode>queue=new ArrayDeque<TreeNode>();

       
       int maxWeight=1;//最大宽度
       queue.add(root);//入队
         while(true)
         {
            int len=queue.size();//当前层节点数
            if(len==0)
              break;
           while(len>0)//如果当前层还有节点
           {
            TreeNode t=queue.poll();
            len--;
  
             if(t.left!=null)
               queue.add(t.left);//下一层节点入队
             if(t.right!=null)
               queue.add(t.right); //下一层节点入队
            }
           maxWeight=Math.max(maxWeight,queue.size());
     }
  return  maxWeight;
}                 

 求宽度 方法2

 

//求叶子数
    public  static int countOfLeaf(TreeNode root)
    {
        int result=0;
        if(root==null)
          return 0;
        if(root.left==null  || root.right==null)
          return 1;
        else
             result= countOfLeaf(root.left)+countOfLeaf(root.right);
        
        return result;
        
        
    }

 

 

 

 参考:http://www.cnblogs.com/xudong-bupt/p/4036190.html

 

posted @ 2015-12-21 20:41  逍的遥  阅读(10894)  评论(0编辑  收藏  举报