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

Vote Vote Cancel Collect Collect Cancel

<< 上一篇: Leetcode PHP题解--D33 700. Search in a Binary Search Tree

>> 下一篇: Leetcode基础刷题之PHP解析(258. Add Digits)