Leetcode PHP题解--D92 606. Construct String from Binary Tree

栏目: PHP · 发布时间: 6年前

内容简介:输出二叉树的节点值。子树内容用半角括号括住,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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Persuasive Technology

Persuasive Technology

B.J. Fogg / Morgan Kaufmann / 2002-12 / USD 39.95

Can computers change what you think and do? Can they motivate you to stop smoking, persuade you to buy insurance, or convince you to join the Army? "Yes, they can," says Dr. B.J. Fogg, directo......一起来看看 《Persuasive Technology》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

在线进制转换器
在线进制转换器

各进制数互转换器

MD5 加密
MD5 加密

MD5 加密工具