内容简介:输出二叉树的节点值。子树内容用半角括号括住,null值也需要括住。用全局变量保存字符串内容。保存节点值之前,添加括号。
D92 606. Construct String from Binary Tree
题目链接
606. Construct String from Binary Tree
题目分析
输出二叉树的节点值。子树内容用半角括号括住,null值也需要括住。
思路
用全局变量保存字符串内容。保存节点值之前,添加括号。
注意,不能在节点值为null时也加括号。而是只在左子树为空,而右子树不为空时,才要把左子树的null部分用括号代替。
最终代码
<?php
/**
* 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 {
protected $str = '';
/**
* @param TreeNode $t
* @return String
*/
function tree2str($t) {
$this->str .= $t->val;
if(!is_null($t->left)){
$this->str .= '(';
$this->tree2str($t->left);
$this->str .= ')';
}
if(!is_null($t->right)){
if(is_null($t->left)){
$this->str .= '()';
}
$this->str .= '(';
$this->tree2str($t->right);
$this->str .= ')';
}
return $this->str;
}
}
若觉得本文章对你有用,欢迎用 爱发电 资助。
以上所述就是小编给大家介绍的《Leetcode PHP题解--D92 606. Construct String from Binary Tree》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Effective Python
布雷特·斯拉特金(Brett Slatkin) / 爱飞翔 / 机械工业出版社 / 2016-1 / 59
用Python编写程序,是相当容易的,所以这门语言非常流行。但若想掌握Python所特有的优势、魅力和表达能力,则相当困难,而且语言中还有很多隐藏的陷阱,容易令开发者犯错。 本书可以帮你掌握真正的Pythonic编程方式,令你能够完全发挥出Python语言的强大功能,并写出健壮而高效的代码。Scott Meyers在畅销书《Effective C++》中开创了一种以使用场景为主导的精练教学方......一起来看看 《Effective Python》 这本书的介绍吧!