1. 程式人生 > >Leetcode PHP題解--D92 606. Construct String from Binary Tree

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;
    }
}

若覺得本文章對你有用,歡迎用