【求助】高分求助二叉树路劲问题
各位大虾,求教一个问题,如下图所示
二叉树每个节点按照图中所示进行编号,假如输入某些叶子节点的编号,打印输出这些叶子节点到根节点所经过的中间节点的并集。
图中,输入0001 0011 0110 1001 就打印输出0 1 00 01 10 000 001 011 100
求各位大虾帮忙!!在线等!
[解决办法]
看你这么恳切,没办法,写了一个。。。测试通过的哦。。
#include <iostream>
#include <string>
#include <list>
using namespace std;
const int MAX_LEVEL = 4;
struct NODE
{
stringValue;
boolOutput;// 是否需要输出。
NODE*Parent;
NODE*LeftChild;
NODE*RightChild;
NODE()
:Value(""), Output(false), Parent(NULL), LeftChild(NULL), RightChild(NULL)
{}
NODE(string v)
:Value(v), Output(false), Parent(NULL), LeftChild(NULL), RightChild(NULL)
{}
};
void AddLefitChild(NODE* parent, int level);
void AddRightChild(NODE* parent, int level);
void AddLeftChild(NODE* parent, int level)
{
if (level >= MAX_LEVEL)
{
return;
}
string v = parent->Value;
v += "0";
NODE* pNode = new NODE(v);
AddLeftChild(pNode, level + 1);
AddRightChild(pNode, level + 1);
parent->LeftChild = pNode;
pNode->Parent = parent;
}
void AddRightChild(NODE* parent, int level)
{
if (level >= MAX_LEVEL)
{
return;
}
string v = parent->Value;
v += "1";
NODE* pNode = new NODE(v);
AddLeftChild(pNode, level + 1);
AddRightChild(pNode, level + 1);
parent->RightChild = pNode;
pNode->Parent = parent;
}
void OutputTree(const list<NODE*>& nl, bool all)
{
if (nl.empty())
{
return;
}
list<NODE*> cnl;
for (list<NODE*>::const_iterator itr = nl.begin(); itr != nl.end(); itr++)
{
if (!all)
{
if ((*itr)->Output)
{
cout<<(*itr)->Value<<"";
}
}
else
{
cout<<(*itr)->Value<<"";
}
if ((*itr)->LeftChild != NULL && (*itr)->RightChild != NULL)
{
cnl.push_back((*itr)->LeftChild);
cnl.push_back((*itr)->RightChild);
}
}
cout<<endl;
OutputTree(cnl, all);
}
NODE* FindNode(NODE* parent, string nv)
{
if (NULL == parent)
{
return NULL;
}
if (nv == parent->Value)
{
return parent;
}
NODE* pNode = FindNode(parent->LeftChild, nv);
if (NULL != pNode)
{
return pNode;
}
pNode = FindNode(parent->RightChild, nv);
if (NULL != pNode)
{
return pNode;
}
return NULL;
}
void MarkPath(NODE* pNode)
{
while(NULL != pNode->Parent)
{
pNode = pNode->Parent;
pNode->Output = true;
}
}
void main()
{
// 手动构建树(实际运用中,应该是自动构建的)
NODE* pNode = new NODE();// root
AddLeftChild(pNode, 0);
AddRightChild(pNode, 0);
list<NODE*> nl;
nl.push_back(pNode);
cout<<"构建的树节点:"<<endl;
OutputTree(nl, true);
// 设置输出
string leaf[] = {"0001", "0011", "0110", "1001"};
cout<<endl<<endl<<"需要查找的叶子:";
for (int i = 0; i< 4; i++)
{
cout<<leaf[i]<<",";
}
cout<<endl<<endl<<endl;
for (int i = 0; i< 4; i++)
{
// 找到叶节点
NODE* leafn = FindNode(pNode, leaf[i]);
if(NULL != leafn)
{
MarkPath(leafn);
}
}
cout<<"查找后的路径:"<<endl;
OutputTree(nl, false);
int ccc;
cin>>ccc;
}
输出: