avatar
问个打印树的问题# JobHunting - 待字闺中
x*n
1
大家好,想问一个基础的问题。假如有一个二叉树,
A
B C
怎么打印出AB, AC,就是从根到各个叶子结点的路径?请问有什么好的方法吗。谢谢!
avatar
r*y
2
recursion?



【在 x***n 的大作中提到】
: 大家好,想问一个基础的问题。假如有一个二叉树,
: A
: B C
: 怎么打印出AB, AC,就是从根到各个叶子结点的路径?请问有什么好的方法吗。谢谢!

avatar
v*n
3
DFS,全路径入栈,每次到底就打印全栈
avatar
P*c
4
这个跟recursion应该是一样的。

【在 v***n 的大作中提到】
: DFS,全路径入栈,每次到底就打印全栈
avatar
v*n
5
recursion是系统帮你管理栈
non-recursion实现得自己管理栈的
问题在于recursion实现的话怎么去遍历栈呢?

【在 P**********c 的大作中提到】
: 这个跟recursion应该是一样的。
avatar
i*e
6
//Hope it works
print_bt(Node *p, string &a)
{
if(p->left)
{
a.push_back(p->data);
print_bt(p->left, a);
}
else if(p->right)
{
a.erase(a.rbegin()); //a.pop_back
a.push_back(p->data); //remove its sibling & add its data
print_bt(p->right, a);
}
else //leaf ?
{
cout << a << endl;
}
}
avatar
v*n
7
你的assumption太强了
不是一定都有左右子树的
而且你这个也没有对每条路经提供完整的从root开始的历史

【在 i*****e 的大作中提到】
: //Hope it works
: print_bt(Node *p, string &a)
: {
: if(p->left)
: {
: a.push_back(p->data);
: print_bt(p->left, a);
: }
: else if(p->right)
: {

avatar
c*p
8
#define DELIMITER '-'
void print_btree(node* root, const string path)
{


if (root == NULL)
return;
// Valid for single-letter named nodes;
string new_path = path + root->name;
// name delimiter needed otherwise
//string new_path = path + path.size()? DELIMITER : '' + root->name;
cout << new_path << ' ';
print_btree(root->left, new_path);
print_btree(root->right, new_path);
//return;
}
int main()
{
// create a btree rooted at btree_root;
print_btree(btree_root, string(""));
return;
}



【在 x***n 的大作中提到】
: 大家好,想问一个基础的问题。假如有一个二叉树,
: A
: B C
: 怎么打印出AB, AC,就是从根到各个叶子结点的路径?请问有什么好的方法吗。谢谢!

avatar
P*c
9
跟你说的差不多。其实DFS也可以用recursion做哈。
void print_path(tree* root, vector& path){
if(!root)
return;
path.push_back(root);
if(!root->left_child && !root->right_child){
for(int i=0; icout<data<cout<}
else{
if(root->left_child)
print_path(root->left_child, path);
if(root->right_child)
print_path(root->right_child, path);
}
path.pop_back();
}
test tree:
3
1 5
0 2 4 6
-1
output:
3 1 0 -1
3 1 2
3 5 4
3 5 6
这道题我觉得要注意的是不能直接用NULL的时候就全部打出,因为那样每条path都会打
两遍。

【在 v***n 的大作中提到】
: recursion是系统帮你管理栈
: non-recursion实现得自己管理栈的
: 问题在于recursion实现的话怎么去遍历栈呢?

avatar
x*n
10
谢谢啊。其实就一先根遍历,我把问题给想复杂了。recursion总是用不好。

【在 P**********c 的大作中提到】
: 跟你说的差不多。其实DFS也可以用recursion做哈。
: void print_path(tree* root, vector& path){
: if(!root)
: return;
: path.push_back(root);
: if(!root->left_child && !root->right_child){
: for(int i=0; i: cout<data<: cout<: }

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。