ð 111. äºåæ çæå°æ·±åºŠ
2022幎10æ10æ¥
- algorithm
ð 111. äºåæ çæå°æ·±åºŠ
éŸåºŠ: ð
é®é¢æè¿°
è§£æ³ 1 - éåœ
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
// æè·¯ïŒ
// å¶åèç¹ïŒå³å·Šå³åèç¹å空çèç¹
return mySol(root);
}
private int mySol(TreeNode root) {
// éåœç»æ¢æ¡ä»¶
if(root == null) {
return 0;
}
if(root.left == null && root.right == null) {
return 1;
}
if(root.left == null) {
return mySol(root.right) + 1;
}
if(root.right == null) {
return mySol(root.left) + 1;
}
return Math.min(mySol(root.left), mySol(root.right)) + 1;
}
}
èŸåº 1
è§£æ³ 2 - å±åºéå
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
// æè·¯ïŒ
// å±åº - èŸ
å© éå
int res = 0;
if(root == null) {
return res;
}
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()) {
res ++;
int len = queue.size();
for(int i = 0; i < len; i ++) {
TreeNode cur = queue.poll();
if(cur.left == null && cur.right == null) {
return res;
}
if(cur.left != null) {
queue.offer(cur.left);
}
if(cur.right != null) {
queue.offer(cur.right);
}
}
}
return res;
}
}