111Minimum Depth of Binary Tree

来源:互联网 发布:用python直接写utf 编辑:程序博客网 时间:2024/06/10 07:12
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
   public int minDepth(TreeNode root) {
  if(root==null) return 0;
  if(root.left==null&&root.right==null) return 1;
  List<TreeNode> listParent = new ArrayList<TreeNode>();
  List<Integer> listDepth = new ArrayList<Integer>();
  listParent.add(root);
  listDepth.add(1);
  while(!listParent.isEmpty()){
  TreeNode tmpNode = listParent.get(0);
  int tmpDepth = listDepth.get(0);
  listParent.remove(0);
  listDepth.remove(0);
  /*
   * 判断当前节点是否为叶节点,若有返回当前深度
   */
  if(tmpNode.left==null&&tmpNode.right==null){
  return tmpDepth;
  }
  /*
   * 判断当前节点的子节点中是否有叶节点,若有返回当前深度加一
   */
  if(tmpNode.left!=null){
  if(tmpNode.left.left==null&&tmpNode.left.right==null){
  return tmpDepth + 1;
  }else{
  listParent.add(tmpNode.left);
  listDepth.add(tmpDepth + 1);
  }
  }
  
  if(tmpNode.right!=null){
  if(tmpNode.right.left==null&&tmpNode.right.right==null){
  return tmpDepth + 1;
  }else{
  listParent.add(tmpNode.right);
  listDepth.add(tmpDepth + 1);
  }
  }
  }
  
  return listDepth.get(0);
   }
}
0 0
原创粉丝点击