banner
NEWS LETTER

LeetCode-113.路径总和II

Scroll down

题目

  • 难度中等
  • 题目链接https://leetcode-cn.com/problems/path-sum-ii/submissions/
  • 语言: PHP
  • 题目内容

    给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
    说明: 叶子节点是指没有子节点的节点。

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

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

返回:

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

思路

深度优先遍历(递归),记录遍历路径,如符合条件则输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php

/**
* Definition for a binary tree node.
* class TreeNode {
* public $val = null;
* public $left = null;
* public $right = null;
* function __construct($value) { $this->val = $value; }
* }
*/
class Solution {

protected $res = [];
/**
* @param TreeNode $root
* @param Integer $sum
* @return Integer[][]
*/
function pathSum($root, $sum) {
$this->dfs($root, $sum, []);
return $this->res;
}

/**
* 深度优先遍历
*/
function dfs($root, $sum, $arr) {
if ($root->val === null) {
return [];
}
// 记录遍历路径
$arr[] = $root->val;
if ($root->left === null && $root->right === null) {
// 如条件符合,返回路径
if ($sum === $root->val) {
$this->res[] = $arr;
// return $this->res;
}
return [];
}
$sum -= $root->val;
$this->dfs($root->left, $sum, $arr);
$this->dfs($root->right, $sum, $arr);
}
}
其他文章
目录导航
  1. 1. 题目
请输入关键词进行搜索