您的位置:首页 > 理论基础 > 数据结构算法

面试题-二元树中和为某一值的所有路径[数据结构]

2012-09-15 16:34 295 查看
题目:输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。打印出和与输入整数相等的所有路径。

例如输入整数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

};

解题:

配合自己写的二叉树头文件,参见
http://blog.csdn.net/emiyasstar__/article/details/7981493
template<typename T>
void BinartSearchTree<T>::searchPath(Node*&  node,vector<T>& path,T& sum,T& target)
{

if(node==NULL)
{

return;
}

path.push_back(node->t);
sum=sum+node->t;
if(node->leftNode==NULL&&node->rightNode==NULL)
{
if(sum==target)
{
for(vector<T>::iterator itr=path.begin();itr!=path.end();itr++)
{
cout<<(*itr)<<" ";
}
cout<<endl;
}

}

searchPath(node->leftNode,path,sum,target);
searchPath(node->rightNode,path,sum,target);

sum=sum-node->t;
path.pop_back();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: