首页 > 其他 > 详细

Maximum Depth of Binary Tree-求二叉树高度

时间:2015-06-24 12:23:47      阅读:90      评论:0      收藏:0      [点我收藏+]
非递归:
public static int maxDepth(TreeNode root){ if(root==null) return 0; Queue<TreeNode> q=new LinkedList<TreeNode>(); q.offer(root); int enQueNum=1; int visitedNum=0; int lastLevNum=1; //做标记 标记到每层最后的节点 当visitedNum与它相等时本层结束 int height=0; while(!q.isEmpty()){ TreeNode now=q.poll(); visitedNum++; if(now.left!=null){ q.offer(now.left); enQueNum++; } if(now.right!=null){ q.offer(now.right); enQueNum++; } if(visitedNum==lastLevNum){ height++; lastLevNum=enQueNum;//lastLevNum的值赋为此时最后进队列的节点数值也是本层的最后节点 } } return height; }

 递归:

public static int maxDepth2(TreeNode root){
            if(root==null) return 0;            
            int leftHeight=0;
            int rightHeight=0;
            leftHeight=maxDepth2(root.left);
            rightHeight=maxDepth2(root.right);
            return leftHeight>rightHeight?leftHeight+1:rightHeight+1;
     }

 

Maximum Depth of Binary Tree-求二叉树高度

原文:http://www.cnblogs.com/hhhhh/p/4597165.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!