面试题34. 二叉树中和为某一值的路径

https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/

var path = [Int]()
var result = [[Int]]()

func pathSum(_ root: TreeNode?, _ sum: Int) -> [[Int]] {
    pathSumAction(root, sum)
    return result
}

func pathSumAction(_ root: TreeNode?, _ sum: Int) {
    if root == nil {
        return
    }
    var Sum = sum
    //记录经过的路径
    path.append(root!.val)
    Sum = Sum - root!.val
    //判断路径是否符合
    if Sum == 0 && root?.left == nil && root?.right == nil {
        result.append(path)
    }
    //前序遍历
    pathSumAction(root?.left, Sum)
    pathSumAction(root?.right, Sum)
    //返回上一节点路径
    path.removeLast()
}

你可能感兴趣的:(面试题34. 二叉树中和为某一值的路径)