Binary Tree Path Sum(lintcode 376)

Description

Given a binary tree, find all paths that sum of the nodes in the path equals to a given number target.

A valid path is from root node to any of the leaf nodes.

Example

Given a binary tree, and target = 5:

    1
   / \
  2   4
 / \
2   3

return

[
  [1, 2, 2],
  [1, 4]
]

Interface

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root the root of binary tree
     * @param target an integer
     * @return all valid paths
     */
    public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) {
        // Write your code here
    }
}

Solution

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root the root of binary tree
     * @param target an integer
     * @return all valid paths
     */
    //private List<List<Integer>> result;

    public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) {
        // Write your code here
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        ArrayList<Integer> path = new ArrayList<Integer>();
        path.add(root.val);
        traverse(root, target, path, root.val, result);
        return result;
    }

    private void traverse(TreeNode root, int target, ArrayList<Integer> path, int sum, List<List<Integer>> result) {
        if (root.left == null && root.right == null) {
            if (target == sum) {
                result.add(new ArrayList<Integer>(path));
            }
            return;
        }

        if (root.left != null) {
            path.add(root.left.val);
            traverse(root.left, target, path, sum + root.left.val, result);
            path.remove(path.size() - 1);
        }

        if (root.right != null) {
            path.add(root.right.val);
            traverse(root.right, target, path, sum + root.right.val, result);
            path.remove(path.size() - 1);
        }
    }
}

results matching ""

    No results matching ""