Hello,
I also just finished a course on data structures and algorithms at Georgia Tech. The methodolgy that the professor had taught was to use "pointer reinforcement" while traversing trees e.g. "current.left = sum(current.left, sum - current.val, values, list);" or "root = sum(root, targetSum, values, list);" for this question:
https://leetcode.com/problems/path-sum-ii/
The code works fine, but I just saw other people's solutions and I am wondering if this "pointer reinforcement" is bad practice... it seems in more difficult problems, it is a much better way to handle edge cases, but I don't see anyone using this practice. The class I took was really good, but I don't see anyone using this methodology and rarely see this terminology "pointer reinforcement"... so it makes me think, it must be bad practice.
It looks like most people use "Look-Ahead" strategy for pointers, which has many more edge cases in more complex scenarios. It didn't phase me until I looked at other solutions and started realizing no one has solutions that look like mine for recursion because I am always wrapping my recursive methods.
Any recommendations? Do interviewers care that you use this different strategy for pointers? Why are all solutions written with Look-Ahead strategy?
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
List<Integer> values = new LinkedList<>();
List<List<Integer>> list = new LinkedList<>();
root = sum(root, targetSum, values, list);
return list;
}
public TreeNode sum(TreeNode current, int sum, List<Integer> values, List<List<Integer>> list) {
if(current == null) return current;
values.add(current.val);
if(current.val == sum && current.left == null && current.right == null) {
list.add(new LinkedList<Integer>(values));
} else {
current.left = sum(current.left, sum - current.val, values, list);
current.right = sum(current.right, sum - current.val, values, list);
}
values.remove(values.size() - 1);
return current;
}