题目:
解答:
方法一:递归
我们可以使用递归的方法得到二叉树的前序遍历。在递归时,根据题目描述,我们需要加上额外的括号,会有以下4中情况。
考虑完上面4种情况,我们就可以得到最终的字符串。
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 string tree2str(TreeNode *root) 13 { 14 if(root == NULL) 15 return ""; 16 17 std::string str = std::to_string(root->val); 18 19 if(root->left == NULL && root->right == NULL) 20 return str + ""; 21 22 if(root->right == NULL) 23 return str + "("+tree2str(root->left)+")"; 24 25 return str + "("+tree2str(root->left)+")("+tree2str(root->right)+")"; 26 } 27 };
原文:https://www.cnblogs.com/ocpc/p/12821837.html