Binary Tree Path Sum II

本文介绍了一种算法,用于查找二叉树中所有节点值之和等于给定目标值的路径。路径无需从根节点开始或在叶节点结束,但必须沿直线向下延伸。文章提供了Java实现代码。

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

注意点:该题目在计算获得 target == 0 后,不能直接返回,需要在继续向下寻找

java

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> preorder = preOrder(root);
        List<Integer> path = new ArrayList<>();
        for (TreeNode node : preorder) {
            path.add(node.val);
            dfs(result, path, target - node.val, node);
            path.clear();
        }
        return result;
    }
    private List<TreeNode> preOrder(TreeNode root) {
        List<TreeNode> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        List<TreeNode> left = preOrder(root.left);
        List<TreeNode> right = preOrder(root.right);
        result.add(root);
        result.addAll(left);
        result.addAll(right);
        return result;
    }
    private void dfs(List<List<Integer>> result, List<Integer> path, 
                     int target, TreeNode root) {
        if (target == 0) {
            result.add(new ArrayList<Integer>(path));
        }
        if (root == null) {
            return;
        }          
        if (root.left != null) {
            path.add(root.left.val);
            dfs(result, path, target - root.left.val, root.left);
            path.remove(path.size() - 1);
        }
        if (root.right != null) {
            path.add(root.right.val);
            dfs(result, path, target - root.right.val, root.right);
            path.remove(path.size() - 1);
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ncst

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值