257. 二叉樹的所有路徑-leetcode
阿新 • • 發佈:2020-09-01
257. 二叉樹的所有路徑-leetcode
Table of Contents
1 題目
2 程式碼
/** * 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 { private $ret = []; /** * @param TreeNode $root * @return String[] */ function binaryTreePaths($root) { $this->ret = []; if (empty($root)) { return $this->ret; } $path = $root->val; $this->dfs($root, $path, 1); return $this->ret; } function dfs($root, $path, $isRoot = 0) { if (! $isRoot) { $path = $path."->".$root->val; } if (empty($root->left) && empty($root->right)) { $this->ret[] = strval($path); } if($root->left) { $this->dfs($root->left, $path); } if ($root->right) { $this->dfs($root->right, $path); } } }
3 思路
深度優先遍歷,或者廣度優先遍歷都可以
我這裡加了一個函式的變數 isRoot,有點冗餘,可以通過優化去掉
===
更新時間: 2020-09-01 Tue 13:35
===
天行健,君子以自強不息。
地勢坤,君子以厚德載物。
===