内容简介:输出二叉树的节点值。子树内容用半角括号括住,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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Computing Patterns in Strings
Bill Smyth / Addison Wesley / 2003 / $ 75.00
The computation of patterns in strings is a fundamental requirement in many areas of science and information processing. The operation of a text editor, the lexical analysis of a computer program, the......一起来看看 《Computing Patterns in Strings》 这本书的介绍吧!