求树的最大宽度和最大深度

以你之姓@ 2022-09-26 02:22 235阅读 0赞

原文地址:http://blog.csdn.net/salahelx/article/details/46727499

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

  1. private static int getHeight(BiNode head) {
  2. if(head==null) //结束条件
  3. return 0;
  4. else return 1+Math.max(getHeight(head.left), getHeight(head.right));
  5. }

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

  1. private static int getWidth(BiNode head) {
  2. if(head==null)
  3. return 0;
  4. int max=1;
  5. LinkedList<BiNode>ll=new LinkedList<BiNode>();
  6. ll.add(head);
  7. while(true){
  8. int len=ll.size();
  9. if(len==0)
  10. break;
  11. while(len>0){
  12. BiNode b=ll.poll();
  13. len--;
  14. if(b.left!=null)
  15. ll.add(b.left);
  16. if(b.right!=null)
  17. ll.add(b.right);
  18. }
  19. max=Math.max(max, ll.size());
  20. }
  21. return max;
  22. }

发表评论

表情:
评论列表 (有 0 条评论,235人围观)

还没有评论,来说两句吧...

相关阅读