111.二叉树的最小与最大深度
题目链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
解题思路:
都是层次遍历,判断返回的条件不一样。
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public int minDepth(TreeNode root) { 12 13 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); 14 ArrayList<Integer> list = new ArrayList<>(); 15 ArrayList<TreeNode> queue = new ArrayList<>(); 16 17 if(root==null) 18 return 0; 19 20 int start = 0; 21 int end = 1; 22 queue.add(root); 23 int count=1; 24 while(!queue.isEmpty()) 25 { 26 TreeNode node = queue.remove(0); 27 start++; 28 if(node.left==null&&node.right==null) 29 break; 30 if(node.left!=null) 31 queue.add(node.left); 32 if(node.right!=null) 33 queue.add(node.right); 34 35 36 list.add(node.val); 37 if(start == end) 38 { 39 res.add(list); 40 count++; 41 start = 0; 42 end = queue.size(); 43 list = new ArrayList<>(); 44 } 45 } 46 return count; 47 48 } 49 }
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public int maxDepth(TreeNode root) { 12 13 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); 14 ArrayList<Integer> list = new ArrayList<>(); 15 ArrayList<TreeNode> queue = new ArrayList<>(); 16 17 if(root==null) 18 return 0; 19 20 int start = 0; 21 int end = 1; 22 queue.add(root); 23 int count=0; 24 while(!queue.isEmpty()) 25 { 26 TreeNode node = queue.remove(0); 27 start++; 28 if(node.left!=null) 29 queue.add(node.left); 30 if(node.right!=null) 31 queue.add(node.right); 32 list.add(node.val); 33 if(start == end) 34 { 35 res.add(list); 36 count++; 37 start = 0; 38 end = queue.size(); 39 list = new ArrayList<>(); 40 } 41 } 42 return count; 43 44 } 45 }
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { int result = 0;//最大深度 public int maxDepth(TreeNode root) { if (root == null) { return 0; } result = Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; return result; } }