描述
您需要從包含括號和整數的字符串中構造一個二叉樹。
整個的輸入表示一個二叉樹。它包含一個整數,或零,或兩對括號。該整數表示根的值,而一對括號包含一個具有相同結構的子二叉樹。
如果父節點存在,您總是首先開始構造它的左子節點。
在輸入字符串中只有'(',')','-'和'0' ~ '9'。
空樹表示爲“”而不是“()”。
樣例
給定 s = “4(2(3)(1))(6(5))”, 返回表示下面樹的節點:
4
/ \
2 6
/ \ /
3 1 5
思路
#ifndef C880_H
#define C880_H
#include<iostream>
#include<string>
#include<algorithm>
#include<stack>
using namespace std;
class TreeNode{
public:
int val;
TreeNode *left, *right;
TreeNode(int val){
this->val = val;
this->left = this->right = NULL;
}
};
class Solution {
public:
/**
* @param s: a string
* @return: a root of this tree
*/
TreeNode * str2tree(string &s) {
// write your code here
if (s.empty())
return NULL;
//s只包含數字,直接構造節點
if (s.find("(") == string::npos)
{
TreeNode *root = new TreeNode(stoi(s));
return root;
}
int beg = s.find("(");//s中第一次出現"("的位置
int end = getPos(s, beg);//與beg的"("對應")"的位置
TreeNode *root = new TreeNode(stoi(s.substr(0, beg)));//提取開始位置表示的數字來構建節點
string l = s.substr(beg + 1, end - beg - 1);//左子樹代表的字符串
root->left = str2tree(l);
//構建右子樹
if (end == s.size() - 1)
root->right = NULL;
else
{
string r = s.substr(end + 2, s.size() - end - 3);
root->right = str2tree(r);
}
return root;
}
//找到與第一個"("對應的")"
int getPos(string &s, int beg)
{
stack<int> stack;
stack.push(s[beg]);
int i = beg + 1;
while (!stack.empty()&&i<s.size())
{
if (s[i] == '(')
stack.push(s[i]);
else if (s[i] == ')')
stack.pop();
++i;
}
return i - 1;
}
};
#endif