面试题-二元树中和为某一值的所有路径[数据结构]
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
例如输入整数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(); }
相关文章推荐
- 程序员面试题精选100题(04)-二元树中和为某一值的所有路径[数据结构]
- 程序员面试题精选100题(04)-二元树中和为某一值的所有路径[数据结构]
- 程序员面试题精选100题(04)-二元树中和为某一值的所有路径[数据结构]
- 程序员面试题精选100题(04)-二元树中和为某一值的所有路径[数据结构]
- 数据结构练习(03)二元树中和为某一值的所有路径
- 二元树中和为某一值的所有路径[数据结构]
- 程序员面试题精选100题(04)-二元树中和为某一值的所有路径[数据结构] 分类: 剑指offer 2014-11-03 09:05 117人阅读 评论(0) 收藏
- 二元树中和为某一值的所有路径[数据结构]
- 二元树中和为某一值的所有路径
- 数据结构面试题1.2.5-在二元树中找出和为某一值的所有路径
- 二元树中和为某一值的所有路径
- 二元树中和为某一值的所有路径
- 二元树中和为某一值的所有路径
- 二元树中和为某一值的所有路径
- 二元树中和为某一值的所有路径
- 二元树中和为某一值的所有路径(递归与非递归的方法)
- 程序员面试题精选100题(04)-二元树中和为某一值的所有路径
- 二元树中和为某一值的所有路径
- 二元树中和为某一值的所有路径
- 二元树中和为某一值的所有路径