You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.
The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree.
Example:
Input: Binary tree: [1,2,3,4]
1
/ \
2 3
/
4
Output: "1(2(4))(3)"
Approach:
C++
#include <bits/stdc++.h>using namespace std;//struct for treenodestruct TreeNode{int data;TreeNode *left;TreeNode *right;TreeNode(int data){this->data = data;this->left = NULL;this->right = NULL;}};string tree2str(TreeNode *t){if (t == NULL)return "";string str = to_string(t->data);if (t->left){str += "(" + tree2str(t->left) + ")";}else if (t->right)str += "()";if (t->right)str += "(" + tree2str(t->right) + ")";return str;}int main(){TreeNode *root = new TreeNode(1);root->left = new TreeNode(2);root->right = new TreeNode(3);root->left->left = new TreeNode(4);cout << tree2str(root);return 0;}
No comments:
Post a Comment