257. Binary Tree Paths

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

    private $result = [];

    /**
     * @param TreeNode $root
     * @return String[]
     */
    function binaryTreePaths($root) {
        $this->dfs($root, '');
        return $this->result;
    }

    function dfs($node, $path) {
        if ($node == null) {
            return;
        }
        if ($path == '') {
            $path = (string)$node->val;
        } else {
            $path .= "->$node->val";
        }
        // 末節點寫入路徑結果
        if (!$node->left && !$node->right) {
            $this->result[] = $path;
            return;
        }

        $this->dfs($node->left, $path);
        $this->dfs($node->right, $path);
    }
}

Last updated