LeetCode: 求二叉树的最小深度

java代码 求解二叉树的最小深度

package tree;

import java.util.LinkedList;
import java.util.Queue;

class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode(int x) { val = x; }
   }

public class height {
     public static int run(TreeNode root) {
         //求给定二叉树的最小深度。
         //最小深度是指树的根结点到最近叶子结点的最短路径上结点的数量
         /**
          * 思路一:深度优先搜索(DFS),利用递归的思想。

                    若为空树返回0;
                    
                    若左子树为空,则返回右子树的最小深度+1;(加1是因为要加上根这一层,下同)
                    
                    若右子树为空,则返回左子树的最小深度+1;
                    
                    若左右子树均不为空,则取左、右子树最小深度的较小值,+1;
          */
         if(root == null) return 0;
         if(root.left == null) return run(root.right)+1;
         if(root.right == null) return run(root.left)+1;
         int leftheight = run(root.left);
         int rightheight = run(root.right);
         return (leftheight < rightheight) ? (leftheight + 1) : (rightheight + 1);
     }
     
     //广度优先搜索(BFS),利用队列的思想,层序遍历,找到第一个叶子结点的层数
     public static int run1(TreeNode root) {
         Queue<TreeNode> queue = new LinkedList<TreeNode>();
         if(root == null)  return 0;
         int depth = 0;
         queue.offer(root);
         while(!queue .isEmpty()) {
            //当前待遍历层的结点数
             int size = queue.size();
             depth++;
            //遍历当前层
             for(int i = 0;i < size;i++) {
                 TreeNode tmp = queue.peek();
                 if(tmp.left != null)
                     queue.add(tmp.left);
                 if(tmp.right != null)
                     queue.add(tmp.right);
                 
                 queue.poll();
                 if(tmp.left == null && tmp.right == null)    
                     return depth;
             }
         }
         return -1;
     }
     
     public static void main(String[] args) {
         TreeNode root = new TreeNode(1);
         root.left = new TreeNode(2);
         root.right = new TreeNode(3);
         root.left.left = new TreeNode(4);
         root.left.right = new TreeNode(5);
         //root.right.left = new TreeNode(6);
         //root.right.right = new TreeNode(7);
         System.out.println(run1(root) + "-------");
    }
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值