这是我在牛客网做的leetcode题 题目是 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. 中文大意是:求解二叉树的最小深度 /** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ /** 求解二叉树的最小深度,用递归的方法解决 */
public class Solution { public int run(TreeNode root) { if(root == null){ return 0; } if(root.right == null){ return 1+run(root.left); } if(root.left == null){ return 1+run(root.right); } if(root.right !=null && root.left != null){ return 1+Math.min(run(root.right),run(root.left)); } return -1; } }
接下来,做个延伸,求解二叉树的最大深度,还是一递归的方式求解(有时间可以试试深度优先搜索DFS思维)
public int runMax(TreeNode root){ return root== null ?0:Math.max(runMax(root.left), runMax(root.right)); }