给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
struct Node
{
int value;
Node* left;
Node* right;
};
vector<string> printRoutes(Node* root)
{
stack<Node*> s;
s.push(root);
string str = "";
vector<string> ret;
while(!s.empty())
{
root = s.top();
s.pop();
if(root->right) s.push(root->right);
if(root->left) s.push(root->left);
str += root->value;
if(root->left == NULL && root->right == NULL)
{
ret.push_back(str);
str.erase(str.size() - 1 , 1);
}
}
return ret;
}
int main()
{
Node a , b , c;
a.value = 'a';
a.left = &b;
a.right = &c;
b.value = 'b';
b.left = NULL;
b.right = NULL;
c.value = 'c';
c.left = NULL;
c.right = NULL;
vector<string> ret = printRoutes(&a);
for(auto& str:ret)
{
cout<<str<<endl;
}
}