题目来源
题目描述
题目的意思是子节点需要用()来包裹。举例来说,二叉树[root,left,right],则转换为root(left)(right)。如果只有left为空节点,则输出root()(right);如果只有right为空节点则可以忽略右节点的(),输出为root(left)。
题目解析
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
递归
string tree2str(TreeNode* root) {
if(root == NULL){
return "";
}
if(root->left != NULL && root->right != NULL){
return to_string(root->val) + "(" + tree2str(root->left) + ")" + "(" + tree2str(root->right) + ")";
}
if(root->left == NULL && root->right != NULL){
return to_string(root->val) + "()" + "(" + tree2str(root->right) + ")";
}
if(root->left != NULL && root->right == NULL){
return to_string(root->val) + "(" + tree2str(root->left) + ")";
}
return to_string(root->val) ;
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private StringBuilder stringBuilder = new StringBuilder();
public String tree2str(TreeNode t) {
helper(t);
return stringBuilder.toString();
}
private void helper(TreeNode root){
if (root == null){
return;
}
stringBuilder.append(root.val);
if (root.left == null && root.right == null){
return;
}
if (root.left != null){
stringBuilder.append("(");
helper(root.left);
stringBuilder.append(")");
}else{
stringBuilder.append("()");
}
if (root.right != null){
stringBuilder.append("(");
helper(root.right);
stringBuilder.append(")");
}
}
}