您的位置:首页 > 其它

606. Construct String from Binary Tree

2017-09-06 11:04 399 查看
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.

/*C++ Solution*/
/**
* 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:
int travelTree(TreeNode * t,string & str) {
if(t == NULL){
return -1;
}

str.append(to_string(t->val));
if(t->left){
str.append("(");
travelTree(t->left,str);
str.append(")");
}

if(t->right){
if(!t->left){
str.append("()");
}
str.append("(");
travelTree(t->right,str);
str.append(")");
}

return 0;
}

string tree2str(TreeNode* t) {
string str;
travelTree(t,str);

return str;
}
};


/*java solution*/
/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public String str = new String();
public boolean travelTree(TreeNode t) {
if(t == null){
return false;
}

str += Integer.toString(t.val);
if(t.left!=null){
str += "(";
travelTree(t.left);
str += ")";
}

if(t.right!=null){
if(t.left == null){
str += "()";
}
str += "(";
travelTree(t.right);
str += ")";
}

return true;
}
public String tree2str(TreeNode t) {
travelTree(t);
return str;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: