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 36
| class Solution { private static class State { private Integer startDepth; private int minutes; }
public int amountOfTime(TreeNode root, int start) { State state = new State(); dfs(state, root, 0, start); return state.minutes; }
private int dfs(State state, TreeNode root, int depth, int start) { if (root == null) { return 0; } if (root.val == start) { state.startDepth = depth; }
int leftDepth = dfs(state, root.left, depth + 1, start); boolean startInLeftTree = state.startDepth != null; int rightDepth = dfs(state, root.right, depth + 1, start); boolean startInRightTree = !startInLeftTree && state.startDepth != null;
if (root.val == start) { state.minutes = Math.max(state.minutes, Math.max(leftDepth, rightDepth)); } else if (startInLeftTree) { state.minutes = Math.max(state.minutes, state.startDepth - depth + rightDepth); } else if (startInRightTree) { state.minutes = Math.max(state.minutes, state.startDepth - depth + leftDepth); }
return Math.max(leftDepth, rightDepth) + 1; } }
|