D130 257. Binary Tree Paths
Topic link
257. Binary Tree Paths
Subject analysis
Given a binary tree, return the path of all child nodes.
Their thinking
This problem is not too difficult. While traversing first, the collection of the parent nodes is crammed into an array. When the current node is a leaf node, concatenate all nodes into a string, stuffed into the class property. When traversing the right node, it indicates that the current node has been traversed, so it ejected itself from the parent node list.
The final code
/** * 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 {
/ * * *@param TreeNode $root
* @return String[]
*/
private $paths = [];
function binaryTreePaths($root) {
$parents = [];
$this->preOrder($root.$parents);
return $this->paths;
}
function preOrder($node, &$parents){
if(is_null($node->val)){
return;
}
$parents[] = $node->val;
if(is_null($node->left) && is_null($node->right)){
$this->paths[] = implode('- >'.$parents);
array_pop($parents);
return;
}
$this->preOrder($node->left, $parents);
$this->preOrder($node->right, $parents);
array_pop($parents);
return; }}Copy the code
If you find this article useful, you are welcome to subsidize it with love.