606. Construct String from Binary Treephp
輸出二叉樹的節點值。子樹內容用半角括號括住,null值也須要括住。node
用全局變量保存字符串內容。保存節點值以前,添加括號。this
注意,不能在節點值爲null時也加括號。而是隻在左子樹爲空,而右子樹不爲空時,纔要把左子樹的null部分用括號代替。spa
<?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;
}
}
複製代碼
若以爲本文章對你有用,歡迎用愛發電資助。.net