Leetcode基础刷题之PHP解析(257. Binary Tree Paths)

2019-4-15 期一  

 Leetcode基础刷题之PHP解析(226. Invert Binary Tree)

1b0189ded01380acbee00b33ad33d988.png

求二叉树根到叶子节点的所有路径.

如果当前节点没有左右节点的话,说明当前节点已经是叶子节点了,就可以返回根节点到叶子节点的一条路径了.

/**
 * 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 $res=[];
    private $data=[];
    /**
     * @param TreeNode $root
     * @return String[]
     */
    function binaryTreePaths($root) {
       $this->treePath($root);
        return $this->res;
    }
    
    function treePath($root){
        if(!$root){
            return;
        }
        array_push($this->data,$root->val);
        if(!$root->left && !$root->right){
            array_push($this->res,implode('->',$this->data));
        }else{
            $this->treePath($root->left);
            $this->treePath($root->right);
        }
        array_pop($this->data);
    }
}

吴亲库里 has written 35 articles

情绪只是对自己无能的愤怒

积分:1817 等级:P6 职业:php 城市:杭州

0 条回复

登录后才能进行评论,立即登录?