刚看到一个题:
给一个string of nested ternary operations例如a?b?c:d:e,build a tree:root是a,左子树是b?c:d对应的tree ,右子树是e。保证input都是valid的。
嗯,先给自己挖个坑,暂时没空,先放着,感兴趣的也可以自己做一做(2015/1/27)
————————————————————————
今天来把这个坑填上。(2015/2/3)
我假设a,b等就是单个字符。如果不是的话,那需要修改代码才行。
class Expression{
public:
Expression(string str):input(str),currpos(0) {}
TreeNode *parse() const;
bool match(char c) const { if (input[currpos] == c) {currpos++; return true;} return false;}
char readChar() const { return input[currpos++];}
void print(TreeNode* pTree);
void delTree(TreeNode* ptree);
private:
mutable int currpos;
string input;
};
TreeNode* Expression::parse() const
{
TreeNode* pNode = NULL;
char c = readChar();
if (c == '\0') {
return pNode;
}
pNode = new TreeNode(c);
if (match('?')) {
TreeNode* pLeft = parse();
pNode->left = pLeft;
} else {
return pNode;
}
match(':');
TreeNode* pRight = parse();
pNode->right = pRight;
return pNode;
}
void Expression::print(TreeNode* pTree)
{
if (pTree == NULL)
return;
cout << pTree->val;
if (pTree->left != NULL) {
cout << '?';
print(pTree->left);
}
if (pTree->right != NULL) {
cout << ':';
print(pTree->right);
}
}
void Expression::delTree(TreeNode* ptree)
{
if (ptree == NULL)
return;
delTree(ptree->left);
delTree(ptree->right);
delete ptree;
}