classSolution { public List<List<Integer>> pathSum(TreeNode root, int targetSum) { List<List<Integer>> ans = newLinkedList<>(); preorder(ans, newLinkedList<>(), root, targetSum); return ans; }
privatevoidpreorder(List<List<Integer>> ans, List<Integer> path, TreeNode node, int targetSum){ // exitrance if (node == null) { return; }
// add the val of the node into path path.add(node.val);
// if this is a leaf node and its val is equals to target, record this path if (node.val == targetSum && node.left == null && node.right == null) { // note here, we cannot directly add path list to the ans, as it is just // a temp container and would be changed during next track List<Integer> validPath = newLinkedList<>(); validPath.addAll(path); ans.add(validPath); }
// if there are children nodes, recursivelly call this func if (node.left != null) { preorder(ans, path, node.left, targetSum - node.val); // backtrack path.remove(path.size() - 1); }
public TreeNode buildmyThree(int[] preorder, int preBeginIndex, int preEndIndex, int[] inorder, int inBeginIndex, int inEndIndex) { // when [preBeginIndex, preEndIndex) has no element, return null; if (preBeginIndex >= preEndIndex) { returnnull; }
// left branch // the key here is how to make sure the next range of preorder array and inorder array // deal with the inorder array first, as we know where to devide it into two partitions intdevideInorderIndex=0; for (inti=0; i < inorder.length; i++) { if (inorder[i] == rootValue) { devideInorderIndex = i; break; } }
// culculate the leftTreeSize to handle the preOrder array starting Index and size intleftTreeSize= devideInorderIndex - inBeginIndex;
private TreeNode buildmyTree(int[] inorder, int inStartIndex, int inEndIndex, int[]postorder, int postStartIndex, int postEndIndex) { // if there is no elements in [inStartIndex, inEndIndex) then return if (inStartIndex >= inEndIndex) { returnnull; }
// the last element in postorder is the root of the whole tree introotValue= postorder[postEndIndex - 1];
TreeNoderoot=newTreeNode(rootValue);
// find the index of rootValue in inorder array to divide the inOrder array into two partitions
introotValueIndexAtInOrder=0; for (inti=0; i < inorder.length; i++) { if (inorder[i] == rootValue) { rootValueIndexAtInOrder = i; break; } }
// the next step is recursively call this function to get the left node and right node root.left = buildmyTree( inorder, inStartIndex, rootValueIndexAtInOrder, postorder, postStartIndex, postStartIndex + leftPostOrderArraySize);