Binary Tree Path Sum II

来源:互联网 发布:java合并单元格某一列 编辑:程序博客网 时间:2024/06/17 08:49

Your are given a binary tree in which each node contains a value. Design an algorithm to get all paths which sum to a given value. The path does not need to start or end at the root or a leaf, but it must go in a straight line down.

Example

Given a binary tree:

    1   / \  2   3 /   /4   2

for target = 6, return

[  [2, 4],  [1, 3, 2]]
标注的虽然是简单题,但是做起来并不感觉简单
java
/** * 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>> binaryTreePathSum2(TreeNode root, int target) {        // write your code here        List<List<Integer>> result = new ArrayList<>();        if (root == null) {            return result;        }        List<TreeNode> path = preOrder(root);        List<Integer> list = new ArrayList<>();        for (TreeNode node : path) {            list.add(node.val);            dfs(node, result, list, target - node.val);            list.clear();        }        return result;    }    private List<TreeNode> preOrder(TreeNode root) {        List<TreeNode> list = new ArrayList<>();        if (root == null) {            return list;        }        List<TreeNode> left = preOrder(root.left);        List<TreeNode> right = preOrder(root.right);        list.add(root);        list.addAll(left);        list.addAll(right);        return list;    }    private void dfs(TreeNode node,                      List<List<Integer>> result,                      List<Integer> path,                     int target) {        if (node == null) {            return;        }        if (target == 0) {            result.add(new ArrayList<Integer>(path));        }        if (node.left != null) {            path.add(node.left.val);            dfs(node.left, result, path, target - node.left.val);            path.remove(path.size() - 1);        }        if (node.right != null) {            path.add(node.right.val);            dfs(node.right, result, path, target - node.right.val);            path.remove(path.size() - 1);        }    }}


python
"""Definition of TreeNode:class TreeNode:    def __init__(self, val):        self.val = val        self.left, self.right = None, None"""class Solution:    """    @param: root: the root of binary tree    @param: target: An integer    @return: all valid paths    """    def binaryTreePathSum2(self, root, target):        # write your code here        if root is None:            return []        nodes = self.inOrder(root)        result = []        for ele in nodes:            path = [ele.val]            self.dfs(ele, result, path, target - ele.val)        return result            def inOrder(self, root):        if root is None:            return []        left = self.inOrder(root.left)        right = self.inOrder(root.right)        return [root] + left + right            def dfs(self, root, result, path, target):        if root is None:            return        if target == 0:            result.append(path[:])                    if root.left is not None:            path.append(root.left.val)            self.dfs(root.left, result, path, target - root.left.val)            path.pop()        if root.right is not None:            path.append(root.right.val)            self.dfs(root.right, result, path, target - root.right.val)            path.pop()


原创粉丝点击