Skip to content

Latest commit

 

History

History
182 lines (152 loc) · 3.73 KB

File metadata and controls

182 lines (152 loc) · 3.73 KB

题目描述

输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。

示例:

给定如下二叉树,以及目标和 sum = 22

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

返回:

[
   [5,4,11,2],
   [5,8,4,5]
]

提示:

  1. 节点总数 <= 10000

解法

先序遍历+路径记录。

Python3

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
        res, path = [], []

        def dfs(root, sum):
            if not root:
                return
            path.append(root.val)
            target = sum - root.val
            if target == 0 and not (root.left or root.right):
                res.append(list(path))
            dfs(root.left, target)
            dfs(root.right, target)
            path.pop()
        
        dfs(root, sum)
        return res

Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private List<List<Integer>> res;
    private List<Integer> path;
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        res = new ArrayList<>();
        path = new ArrayList<>();
        dfs(root, sum);
        return res;

    }

    private void dfs(TreeNode root, int sum) {
        if (root == null) {
            return;
        }
        path.add(root.val);
        int target = sum - root.val;
        if (target == 0 && root.left == null && root.right == null) {
            List<Integer> t = new ArrayList<>(path);
            res.add(t);
        }
        dfs(root.left, target);
        dfs(root.right, target);
        path.remove(path.size() - 1);
    }
}

JavaScript

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} sum
 * @return {number[][]}
 */
var pathSum = function(root, sum) {
    if(!root) return []
    let res = []
    function dfs(node,sum,arr) {
        if(!node) return
        arr = [...arr,node.val]
        if(node.val === sum && !node.left && !node.right) {
             res.push(arr)
             return
        }
        dfs(node.left,sum - node.val,arr)
        dfs(node.right,sum - node.val,arr)
    }
    dfs(root,sum,[])
    return res
};

Go

var res [][]int 
func pathSum(root *TreeNode, sum int) [][]int {
    res = [][]int{}
    if root == nil {
        return res
    }
    helper(root, sum, []int{})
    return res
}

func helper(node *TreeNode, target int, ans []int) {
    if node == nil {
        return
    }
    ans = append(ans,node.Val)
    target -= node.Val
    if target == 0 && node.Left == nil && node.Right == nil {
        tmp := make([]int,len(ans))
        copy(tmp,ans)
        res = append(res,tmp)
    } else {
        helper(node.Left, target, ans)
        helper(node.Right, target, ans)
    }
}

...