美文网首页
376. 二叉树的路径和

376. 二叉树的路径和

作者: 叨逼叨小马甲 | 来源:发表于2017-12-05 04:32 被阅读0次

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

一个有效的路径,指的是从根节点到叶节点的路径。
样例

给定一个二叉树,和 目标值 = 5:

    1
    / \
   2   4
  / \
 2   3

返回:

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

代码

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import LintClass.TreeNode;

/**
 * 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 BinaryTreePathSum_376 {
    /*
     * @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
        List<List<Integer>> paths = new ArrayList<List<Integer>>();
        List<Integer> path = new ArrayList<Integer>();
        search(paths, path, target, root);
        
        return paths;
    }
    
    private void search(List<List<Integer>> paths, List<Integer> path, int target, TreeNode root) {
        if(root == null) {
            return;
        }
        
        if(root.left == null && root.right == null && root.val == target) {
            path.add(root.val);
            paths.add(path);
        }
        
        if(root.left != null) {
            List<Integer> left = new ArrayList<Integer>(path);
            left.add(root.val);
            search(paths, left, target - root.val, root.left);
        }
        
        if(root.right != null) {
            List<Integer> right = new ArrayList<>(path);
            right.add(root.val);
            search(paths, right, target - root.val, root.right);
        }
        
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode left_1 = new TreeNode(2);
        TreeNode right_1 = new TreeNode(4);
        TreeNode left_left_2 = new TreeNode(2);
        TreeNode left_right_2 = new TreeNode(3);
        root.left = left_1;
        root.right = right_1;
        root.left.left = left_left_2;
        root.left.right = left_right_2;
        
        BinaryTreePathSum_376 obj = new BinaryTreePathSum_376();
        int target = 5;
        System.out.print(obj.binaryTreePathSum(root, target));
    }
}

相关文章

网友评论

      本文标题:376. 二叉树的路径和

      本文链接:https://www.haomeiwen.com/subject/rvqqixtx.html