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); } }
|