二叉树的路径和

2017-05-22  本文已影响0人  赵仝

给定一个二叉树,找出所有路径中各节点相加总和等于给定 目标值 的路径。一个有效的路径,指的是从根节点到叶节点的路径。

代码:

/**
 * 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) {
        List<List<Integer>> list=new ArrayList<>();
        List<Integer> temp=new ArrayList<>();
        findPath(root,target,temp,list);
        return list;
    }
    
    public void findPath(TreeNode root,int target,List<Integer> temp,List<List<Integer>> path)
    {
        if (root == null)
            return;
        if (root.left == null && root.right == null) {
            if (root.val == target) {
                List<Integer> temp2=new ArrayList<>();
                temp2.addAll(temp);
                temp2.add(root.val);
                path.add(temp2);
            }
        } else {
            temp.add(root.val);
            findPath(root.left, target - root.val, temp,path);
            findPath(root.right, target - root.val, temp,path);
            temp.remove(temp.size() - 1);
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读