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


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题解--D91 175. Combine Two Tables

>> 下一篇: Leetcode PHP题解--D93 171. Excel Sheet Column Number