Leetcode PHP題解--D92 606. Construct String from Binary Tree
阿新 • • 發佈:2019-06-22
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; } }