leetcode minimum-depth-of-binary-tree
题目描述
Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
我的解题思路:问题的关键是遍历,那么就有深度优先和宽度优先的方法,深度优先使用递归,代码更加优雅,需要多多学习,而宽度优先需要队列操作,记住Queue是一个接口,LinkListed是Queue的一个实现类。
在下的代码 时间384ms 空间15100k
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ import java.util.LinkedList; public class Solution { public int run(TreeNode root) { if (root == null) return 0; LinkedList<TreeNode> a = new LinkedList<TreeNode>(); root.val = 1; a.add(root); while (!a.isEmpty()){ TreeNode node = a.poll(); if (node.left != null){ node.left.val = node.val + 1; a.add(node.left); } if (node.right != null){ node.right.val = node.val + 1; a.add(node.right); } if (node.left == null && node.right == null){ return node.val; } } return 0; } }
类似的 时间267ms 空间14928k
import java.util.LinkedList; import java.util.Queue; public class Solution { public int run(TreeNode root) { if(root == null) return 0; if(root.left == null && root.right == null) return 1; int depth = 0; Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while(!queue.isEmpty()){ int len = queue.size(); depth++; for(int i = 0; i < len; i++){ TreeNode cur = queue.poll(); if(cur.left == null && cur.right == null) return depth; if(cur.left != null) queue.offer(cur.left); if(cur.right != null) queue.offer(cur.right); } } return 0; } }
大神代码 时间232ms 空间14404k
public class Solution { public int run(TreeNode root) { if(root==null) return 0; if(root.left==null&&root.right==null) return 1; if(root.left==null) return run(root.right)+1; if(root.right==null) return run(root.left)+1; return Math.min(run(root.left),run(root.right))+1; } }