题目
示例 : 给定如下二叉树,以及目标和 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); } }