[剑指offer][第四章][25]Binary Tree Path Sum

来源:互联网 发布:京东数据罗盘免费版 编辑:程序博客网 时间:2024/05/21 15:41

[LintCode]Binary Tree Path Sum

/** * 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) {        // 2016-04-11 搜索        List<List<Integer>> rst = new ArrayList<List<Integer>>();        List<Integer> list = new ArrayList<Integer>();        help(rst, list, root, target);        return rst;            }        private void help(List<List<Integer>> rst, List<Integer> list, TreeNode root, int left) {        if (root == null) {            return;        }                // 找到一个叶节点        if (root.left == null && root.right == null) {            if (left == root.val) {                list.add(root.val);                rst.add(new ArrayList<Integer>(list));                list.remove(list.size() - 1);            }            return;        }                // 不是叶节点        list.add(root.val);        help(rst, list, root.left, left - root.val);        help(rst, list, root.right, left - root.val);        list.remove(list.size() - 1);    }}


0 0
原创粉丝点击