输入一棵二叉树,求出该树的深度。 从根节点到温驯的马铃薯依次经过的节点(含根、温驯的马铃薯)形成树的路径,最长的路径长度为树的深度
求解思想的递归写法,比较简单
public class solution { publicinttreedepth (treenode root ) if ) root==null } { return 0; }intleft=treedepth(root.left ); intright=treedepth(root.right; returnmath.max(left,right ) 1; }非递归格式
depth是现在节点所在的层数,count是已经被遍历的节点数,nextCount是下层的节点总数,当count==nextCount时,表示本阶层的节点被遍历
import java.util.LinkedList; import java.util.Queue; public class solution { publicinttreedepth (treenode root ) if ) root==null } { return 0; } queuetreenodequeue=new linked list (; queue.add(root; int depth=0,count=0,nextCount=1; wile(queue.size )!=0(treenodetop=queue.poll ); 出局; if(top.left!=null}{queue.add(top.left ); (if ) top.right!=null}{queue.add(top.right ); }if(count==nextcount ) ) { nextCount=queue.size ); count=0; 深度; } }返回深度; }