二叉树的所有路径


二叉树的所有路径

题目

1
2
3
4
5
6
7
8
9
10
给你一个二叉树的根节点 root,按 任意顺序,返回所有从根节点到叶子节点的路径
叶子节点 是指没有子节点的节点

示例 1:
输入:root = [1,2,3,null,5]
输出:["1->2->5","1->3"]

示例 2:
输入:root = [1]
输出:["1"]

解法

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
47
48
49
50
51
52
53
54
55
56
57
58
思路:
遍历二叉树,存在子节点就在字符串后面加上->,将所有路径存储到数组中

代码:
class TreeNode
{
public $val = null;
/**
* @var TreeNode|null
*/
public $left = null;
/**
* @var TreeNode|null
*/
public $right = null;

function __construct($val = 0, $left = null, $right = null)
{
$this->val = $val;
$this->left = $left;
$this->right = $right;
}
}

/**
* @param TreeNode $root
* @return String[]
*/
function binaryTreePaths($root)
{
$paths = [];

$this->treeToList($paths, '', $root);

return $paths;
}

private function treeToList(&$paths, $path, $node)
{
if (!$node->left && !$node->right) {
// 字符串添加子节点的值,并写入数组中
$paths[] = $path . $node->val;

return;
}

// 非子节点,字符串后加上->
$path .= $node->val . '->';

// 递归直到没有子节点
if ($node->left) {
$this->treeToList($paths, $path, $node->left);
}

if ($node->right) {
$this->treeToList($paths, $path, $node->right);
}
}