376. 二叉樹的路徑和

給定一個二叉樹,找出所有路徑中各節(jié)點相加總和等于給定 目標(biāo)值 的路徑。

一個有效的路徑,指的是從根節(jié)點到葉節(jié)點的路徑。
樣例

給定一個二叉樹,和 目標(biāo)值 = 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));
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容