[leetcode]Minimum Depth of Binary Tree
树的递归。要注意对左右子树中有null的处理。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | /** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int minDepth(TreeNode root) { // Start typing your Java solution below // DO NOT write main() function if (root == null ) return 0 ; boolean left = root.left != null ; boolean right = root.right != null ; if (left && right) { int minLeft = minDepth(root.left) + 1 ; int minRight = minDepth(root.right) + 1 ; if (minLeft > minRight) return minRight; else return minLeft; } else if (left) { return minDepth(root.left) + 1 ; } else if (right) { return minDepth(root.right) + 1 ; } else { return 1 ; } } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步