说明:本文参考网友的实现,如有版权问题,请联系我。本文代码在vs2019下运行通过,不过,测试用例测试很完整。
struct BinaryTreeNode {
public:
BinaryTreeNode(int value) {
value_ = value;
left_ = nullptr;
right_ = nullptr;
}
int value_;
BinaryTreeNode* left_;
BinaryTreeNode* right_;
};
//打印二叉树所有从根节点到叶子节点的路径-递归
void get_path(BinaryTreeNode* p, vector
if (nullptr == p->left_ && nullptr == p->right_) {
result.push_back(path);
}
if (p->left_) {
ostringstream ss;
ss << path << "->" << p->left_->value_;
get_path(p->left_, result, ss.str());
}
if (p->right_) {
ostringstream ss;
ss << path << "->" << p->right_->value_;
get_path(p->right_, result, ss.str());
}
}
vector
vector
if (nullptr == root)
return result;
ostringstream ss;
ss << root->value_;
get_path(root, result, ss.str());
return result;
}
//打印二叉树所有从根节点到叶子节点的路径-非递归-深度优先
vector
vector
if (nullptr == root)
return result;
deque
BinaryTreeNode* p = root;
BinaryTreeNode* last_visit = nullptr;
while (p || !s.empty()) {
if (nullptr != p) {
s.push_back(p);
p = p->left_;
}
else {
p = s.back();
if (nullptr == p->right_ || last_visit == p->right_) {
if (nullptr == p->left_ && nullptr == p->right_) {
ostringstream ss;
for (auto it = s.begin(); it != s.end()-1; ++it) {
ss << (*it)->value_ << "->";
}
ss << p->value_;
result.push_back(ss.str());
}
last_visit = p;
s.pop_back();
p = nullptr;
}
else {
p = p->right_;
}
}
}
return result;
}
//打印二叉树所有从根节点到叶子节点的路径-非递归-广度优先
vector
vector
if (nullptr == root)
return result;
queue
queue
BinaryTreeNode* p = nullptr;
ostringstream ss;
q.push(root);
ss.str("");
paths.push(ss.str());
while (!q.empty()) {
p = q.front();
q.pop();
string path = paths.front();
paths.pop();
if (nullptr == p->left_ || nullptr == p->right_) {
ostringstream ss;
ss << path << p->value_;
result.push_back(ss.str());
}
if (nullptr != p->left_) {
ostringstream ss;
ss << path << p->value_ << "->";
q.push(p->left_);
paths.push(ss.str());
}
if (nullptr != p->right_) {
ostringstream ss;
ss << path << p->value_ << "->";
q.push(p->right_);
paths.push(ss.str());
}
}
return result;
}
int main()
{
BinaryTreeNode *root = new BinaryTreeNode(10);
BinaryTreeNode *root_l = new BinaryTreeNode(5);
BinaryTreeNode* root_r = new BinaryTreeNode(20);
root->left_ = root_l;
root->right_ = root_r;
BinaryTreeNode* root_l_l = new BinaryTreeNode(3);
BinaryTreeNode* root_l_r = new BinaryTreeNode(7);
root_l->left_ = root_l_l;
root_l->right_ = root_l_r;
//vector
vector
//vector
for (size_t i = 0; i < result.size(); i++) {
cout << result[i] << endl;
}
return 0;
}