LeetCode题目-257

首页 编程分享 LEET_CODE 正文

leetCode 转载 编程分享 2019-03-03 11:14:21

简介 LeetCode题目-257


✏Leetcode之PHP版题目解析(257. Binary Tree Paths)


✏描述

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


✏题目实例


✏题目分析

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

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

转载链接:https://leetcode.cn/


Tags:


本篇评论 —— 揽流光,涤眉霜,清露烈酒一口话苍茫。


    声明:参照站内规则,不文明言论将会删除,谢谢合作。


      最新评论




ABOUT ME

Blogger:袅袅牧童 | Arkin

Ido:PHP攻城狮

WeChat:nnmutong

Email:nnmutong@icloud.com

标签云