606. Construct String from Binary Treephp
输出二叉树的节点值。子树内容用半角括号括住,null值也须要括住。node
用全局变量保存字符串内容。保存节点值以前,添加括号。this
注意,不能在节点值为null时也加括号。而是只在左子树为空,而右子树不为空时,才要把左子树的null部分用括号代替。.net
<?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; } }
若以为本文章对你有用,欢迎用爱发电资助。code