Skip to content

Latest commit

 

History

History
65 lines (53 loc) · 1.92 KB

257.md

File metadata and controls

65 lines (53 loc) · 1.92 KB

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

2019-04-15 吴亲库里 库里的深夜食堂


✏️描述

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


✏️题目实例

****

✏️题目分析

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

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

联系