首页 > 编程知识 正文

层次遍历二叉树算法完整代码,求完全二叉树的深度

时间:2023-05-04 04:55:11 阅读:166791 作者:1249

输入一棵二叉树,求出该树的深度。 从根节点到温驯的马铃薯依次经过的节点(含根、温驯的马铃薯)形成树的路径,最长的路径长度为树的深度

求解思想的递归写法,比较简单

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; 深度; } }返回深度; }

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。