376.二叉树的路径和

描述

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

样例

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

             1
            / \
           2   4
          / \
         2   3
返回:

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

思路

遍历二叉树,将当前结点值添加到路径,遍历到叶子结点得到每条完整路径,判断路径中各点值是否满足 target,将符合条件路径添加到 result

代码

/**
 * 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>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        
        ArrayList<Integer> path = new ArrayList<>();
        path.add(root.val);
        helper(root, path, root.val, target, result);
        return result;
    }
    
    private void helper(TreeNode root,
                        ArrayList<Integer> path,
                        int sum,
                        int target,
                        List<List<Integer>> result) {
        if (root.left == null && root.right == null) {
            if (sum == target) {
                result.add(new ArrayList<Integer>(path));
                return;
            }
        }
        
        if (root.left != null) {
            path.add(root.left.val);
            helper(root.left, path, root.left.val + sum, target, result);
            path.remove(path.size() - 1);
        }
        
        if (root.right != null) {
            path.add(root.right.val);
            helper(root.right, path, root.right.val + sum, target, result);
            path.remove(path.size() - 1);
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 树的概述 树是一种非常常用的数据结构,树与前面介绍的线性表,栈,队列等线性结构不同,树是一种非线性结构 1.树的定...
    Jack921阅读 9,935评论 1 31
  • B树的定义 一棵m阶的B树满足下列条件: 树中每个结点至多有m个孩子。 除根结点和叶子结点外,其它每个结点至少有m...
    文档随手记阅读 14,581评论 0 25
  • 四、树与二叉树 1. 二叉树的顺序存储结构 二叉树的顺序存储就是用数组存储二叉树。二叉树的每个结点在顺序存储中都有...
    MinoyJet阅读 5,511评论 0 7
  • 本文转自 http://www.cnblogs.com/manji/p/4903990.html二叉树-****你...
    doublej_yjj阅读 3,904评论 0 8
  • 内容整理于鱼c工作室教程 1. 树的基本概念 1.1 树的定义 树(Tree)是n(n>=0)个结点的有限集。 当...
    阿阿阿阿毛阅读 4,965评论 0 1