题目:EPI
提示:思考如何让树的每个节点只被访问一次,就能完成打印任务。
难点在于两点:1、判断一个节点是不是外层节点;2、正确地执行打印顺序。
class tree
{
public:
int data;
shared_ptr<tree> left,right;
tree(const int d):data(d),left(nullptr),right(nullptr){}
tree(const int d,const shared_ptr<tree> &l,const shared_ptr<tree> &r):data(d),left(l),right(r){}
};
void print_right_subtree(const shared_ptr<tree> &root,const bool Isexterior)
{
if(root==nullptr)
return;
//右子树先递归再打印
print_right_subtree(root->left,Isexterior && !root->right);//重要
print_right_subtree(root->right,Isexterior);
if(Isexterior || (root->left==nullptr && root->right==nullptr))
{
cout<<root->data<<"\t";
}
}
void print_left_subtree(const shared_ptr<tree> &root,const bool Isexterior)
{
if(root==nullptr)
return;
//左子树先打印再递归
if(Isexterior || (root->left==nullptr && root->right==nullptr))
{
cout<<root->data<<"\t";
}
//左节点是否为外层节点,由Isexterior决定
print_left_subtree(root->left,Isexterior);
//右节点是否为外层节点,还要看root是否有左节点,千万不要遗漏!!!
print_left_subtree(root->right,Isexterior && !root->left);//重要
}
void print_tree_exterior(const shared_ptr<tree> &root)
{
if(root==nullptr)
return;
cout<<root->data<<"\t";
print_left_subtree(root->left,true);
print_right_subtree(root->right,true);
cout<<endl;
}
//测试代码
shared_ptr<tree> a1(new tree(1));
shared_ptr<tree> a2(new tree(2));
shared_ptr<tree> a3(new tree(3));
shared_ptr<tree> a4(new tree(4));
shared_ptr<tree> a5(new tree(5));
shared_ptr<tree> a6(new tree(6));
shared_ptr<tree> a7(new tree(7));
shared_ptr<tree> a8(new tree(8));
a1->left=a2;
a1->right=a3;
a2->left=a4;
a2->right=a5;
a3->left=a6;
a3->right=a7;
a5->left=a8;
print_tree_exterior(a1);