You need to convert a binary tree into a string of parentheses and integers in the way of a pre-order traversal.
Empty nodes are denoted by a pair of empty parentheses "()". And you need to omit all empty brace pairs that do not affect the one-to-one mapping between the string and the original binary tree.
Example 1:
Input: Two fork tree: [1,2,3,4]
1
/ \
2 3
/
4
output: "1 (2 (4)) (3)"
Interpretation: "1 (2 (4) ()) (3 ())",
after you omit all unnecessary empty brackets,
it will be "1 (2 (4)) (3)".
Example 2:
Input: Two fork tree: [1,2,3,null,4]
1
/ \
2 3
\
4
output: "1 (2 () (4)) (3)"
Explanation: Similar to the first example ,
except that we cannot omit the first pair of parentheses to break the one-to-one mapping between input and output.
/** * Definition for a binary tree node.
* struct TreeNode {* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode (int x): Val (x), left (null), right (NULL) {} *};
*/class Solution {public:string ans;
void Preordertraversal (treenode* root)//pre-order traversal {int left = 0;
if (root) {ans + = to_string (root->val);
if (root->left! = NULL) {left = 1;//flag bit, whether there is an ans + = (';
Preordertraversal (Root->left);
Ans + = ') ';
if (root->right! = NULL) {if (left = = 0)//If there is no right-hand node directly to the node, the description should be output one ()
Ans + = "()";
Ans + = ' (';
Preordertraversal (Root->right);
Ans + = ') ';
}}} string Tree2str (Treenode* t) {preordertraversal (t);
return ans; }
};