class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
int color = image[sr][sc];
if (color != newColor) {
helper(image, sr, sc, color, newColor);
}
return image;
}
private void helper(int[][] image, int y, int x, int old, int newColor) {
if (image[y][x] == old) {
image[y][x] = newColor;
if (y >= 1) helper(image, y-1, x, old, newColor);
if (y < image.length - 1) helper(image, y+1, x, old, newColor);
if (x >= 1) helper(image, y, x-1, old, newColor);
if (x < image[0].length - 1) helper(image, y, x+1, old, newColor);
}
}
}
Runtime: 1 ms, faster than 52.10% of Java online submissions for Flood Fill.
Memory Usage: 44.7 MB, less than 10.46% of Java online submissions for Flood Fill.
재귀를 돌려서 숫자를 바꿔야 하면 사방으로 가주면서 색깔을 바꿔줬읍니다
처음에는 if (color != newColor) 이거 하나 없다고 overflow가 나와서 그거 고치는게 젤 힘들었읍니다
/**
* 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 TreeNode sufficientSubset(TreeNode root, int limit) {
if (helper(root, limit, root.val) < limit) {
return null;
}
return root;
}
private int helper(TreeNode root, int limit, int total) {
if (root.left == null && root.right == null) {
return total;
}
int right = Integer.MIN_VALUE;
int left = Integer.MIN_VALUE;
if (root.left != null) {
left = helper(root.left, limit, total + root.left.val);
if (left < limit) {
root.left = null;
}
}
if (root.right != null) {
right = helper(root.right, limit, total + root.right.val);
if (right < limit) {
root.right = null;
}
}
return Math.max(left, right);
}
}
Runtime: 1 ms, faster than 31.16% of Java online submissions for Insufficient Nodes in Root to Leaf Paths.
Memory Usage: 49.4 MB, less than 5.43% of Java online submissions for Insufficient Nodes in Root to Leaf Paths.
public TreeNode sufficientSubset(TreeNode root, int limit) {
if (root == null)
return null;
if (root.left == null && root.right == null)
return root.val < limit ? null : root;
root.left = sufficientSubset(root.left, limit - root.val);
root.right = sufficientSubset(root.right, limit - root.val);
return root.left == root.right ? null : root;
}
Runtime: 1 ms, faster than 31.16% of Java online submissions for Insufficient Nodes in Root to Leaf Paths.
Memory Usage: 39.5 MB, less than 19.93% of Java online submissions for Insufficient Nodes in Root to Leaf Paths.
루션이는 훨씬 간략하게 썼네요~