题目:输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。打印出和与输入整数相等的所有路径。例如 输入整数22和如下二元树
10
/ \
5 12
/ \
4 7
则打印出两条路径:10, 12和10, 5, 7。
二元树节点的数据结构定义为:
struct BinaryTreeNode // a node in the binary tree
{
int m_nValue; // value of node
BinaryTreeNode *m_pLeft; // left child of node
BinaryTreeNode *m_pRight; // right child of node
10
/ \
5 12
/ \
4 7
则打印出两条路径:10, 12和10, 5, 7。
二元树节点的数据结构定义为:
struct BinaryTreeNode // a node in the binary tree
{
int m_nValue; // value of node
BinaryTreeNode *m_pLeft; // left child of node
BinaryTreeNode *m_pRight; // right child of node
};
看到这个题目,首先想到的是,先找到满足的叶子。但是题目要求是打印从跟节点到叶子的路径,所以还得把路径打出来。
我首先想到的是使用vector容器(代码里面包含的有构造一个最简单的二叉查找树,添加节点,打印整棵树(用中序遍历))
<span style="color:#009900;">#include <iostream>
#include <algorithm>
using namespace std;
class CTwoTree
{
public:
struct BSTreeNode
{
int m_nValue; // value of node
BSTreeNode *m_pLeft; // left child of node
BSTreeNode *m_pRight; // right child of node
};
CTwoTree(){proot = NULL;}
void CAddNode(int m_nValue, BSTreeNode * &p)
{
if(p == NULL)
{
p = new BSTreeNode;
p->m_nValue = m_nValue;
p->m_pLeft = NULL;
p->m_pRight = NULL;
return;
}
if(m_nValue > p->m_nValue)
{
CAddNode(m_nValue, p->m_pRight);
}
else if(p->m_nValue > m_nValue)
{
CAddNode(m_nValue, p->m_pLeft);
}
}
void CAddNode(int m_nValue)
{
CAddNode(m_nValue, proot);
}
void zhongxu(BSTreeNode *root)
{
if(root == NULL)
return;
if(root->m_pLeft != NULL)
{
zhongxu(root->m_pLeft);
}
cout << root->m_nValue << endl;
if(root->m_pRight != NULL)
{
zhongxu(root->m_pRight);
}
}
void printTree()
{
zhongxu(proot);
}
void findSum(int x, BSTreeNode *&p)
{
if(p == NULL)
return;
path.push_back(p);//每次进来先存起来,不满足则pop掉
if(p->m_pLeft != NULL)
{
findSum(x-p->m_nValue,p->m_pLeft);
}
if(p->m_pRight != NULL)
{
findSum(x-p->m_nValue,p->m_pRight);
}
if(x == p->m_nValue && p->m_pLeft == NULL && p->m_pRight == NULL)
{
/********为了打印成逗号间隔的格式**********/
for(int i = 0; i < path.size()-1; i ++)
cout << path.at(i)-> m_nValue<< ",";
cout << path.at(path.size()-1)-> m_nValue << endl;
/********为了返回到上一节点**********/
while(1)
{
if(path.size() >= 1)
{
if(path.at(path.size()-1)->m_pRight == NULL)
path.pop_back();
else
break;
}
else
break;
}
}
else
path.pop_back();//不满足则pop掉
}
void findSum(int x)
{
findSum(x, proot);
}
void deleteAll(BSTreeNode * p)
{
<span style="white-space:pre"> </span>delete p;
}
~CTwoTree()
{<span style="white-space:pre">
</span><span style="white-space:pre"> </span>for_each(path.begin(),path.end(),deleteAll);
}
private:
BSTreeNode *proot;
vector<BSTreeNode*> path;
};
int main(int argc, char *argv[])
{
CTwoTree a;
a.CAddNode(10);
a.CAddNode(6);
a.CAddNode(4);
a.CAddNode(8);
a.CAddNode(14);
a.CAddNode(12);
a.CAddNode(16);
a.printTree();
a.findSum(40);
return 0;
}
</span>