144. Binary Tree Preorder Traversal

二元樹的前序走訪

/**
 * 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 Integer[]
     */
    function preorderTraversal($root) {
        $this->preorder($root);

        return $this->result;
    }

    private function preorder($root) {
        if ($root === null){
            return null;
        }
        
        $this->result[] = $root->val;
        $this->preorder($root->left);
        $this->preorder($root->right);
    }
}

Last updated