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 11 static int wing=[]() 12 { 13 std::ios::sync_with_stdio(false); 14 cin.tie(NULL); 15 return 0; 16 }(); 17 18 class Solution 19 { 20 public: 21 string tree2str(TreeNode* t) 22 { 23 return travel(t); 24 } 25 26 string travel(TreeNode* root) 27 { 28 if(root==NULL) 29 return ""; 30 if(root->left==NULL&&root->right==NULL) 31 return to_string(root->val); 32 else if(root->right==NULL) 33 return to_string(root->val)+"("+travel(root->left)+")"; 34 else 35 return to_string(root->val)+"("+travel(root->left)+")"+"("+travel(root->right)+")"; 36 } 37 };
递归,问题不大,还挺好理解的