面试100题004--二元树中找出和为某一值的所有路径

一刷100题的第三天。

题目:输入一个整数和一棵二元树。
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如 输入整数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
};

答案:

#include <iostream>
#include <vector>
using namespace std;
struct BSTreeNode {
int m_nvalue;
BSTreeNode *m_pleft;
BSTreeNode *m_pright;
};
void addBSTreeNode(BSTreeNode * & pCurrent, int value) {
if (pCurrent == NULL) {
BSTreeNode *pBSTree = new BSTreeNode();
pBSTree->m_nvalue = value;
pBSTree->m_pleft = NULL;
pBSTree->m_pright = NULL;
pCurrent = pBSTree;
}
else {
if (pCurrent->m_nvalue > value) {
addBSTreeNode(pCurrent->m_pleft, value);
}
else if (pCurrent->m_nvalue < value) {
addBSTreeNode(pCurrent->m_pright, value);
}
else {
cout << "this tree has this number!" << endl;
}
}
}
void findPath(BSTreeNode * & pCurrent, int expectedSum, std::vector<int> &path,int &currentSum) {
if (!pCurrent) {
return;
}
currentSum += pCurrent->m_nvalue;
path.push_back(pCurrent->m_nvalue);
bool isLeaf = (!pCurrent->m_pleft&&!pCurrent->m_pright);
if (currentSum == expectedSum&&isLeaf) {
std::vector<int>::iterator iter = path.begin();
for (; iter != path.end();iter++) {
std::cout << *iter << '\t';
}
std::cout << std::endl;
}
if (pCurrent->m_pleft) {
findPath(pCurrent->m_pleft, expectedSum, path,currentSum);
}
if (pCurrent->m_pright) {
findPath(pCurrent->m_pright, expectedSum, path,currentSum);
}
currentSum -= pCurrent->m_nvalue;
path.pop_back();
}
int main() {
BSTreeNode *pRoot = NULL;
addBSTreeNode(pRoot, 10);
addBSTreeNode(pRoot, 5);
addBSTreeNode(pRoot, 4);
addBSTreeNode(pRoot, 7);
addBSTreeNode(pRoot, 12);
std::vector<int> path;
int currentSum = 0;
int expectedSum = 19;
findPath(pRoot, expectedSum, path, currentSum);
return 0;
}


总结:完全是跟着July的答案写的。鄙视自己一下。一开始看明白了自己写一下还各种出错,最后直接把一些部分复制粘贴了,鄙视自己一下。。最后发现原来是查找树的建立操作是先序遍历的,在主函数里添加数字加反了,晕死。。。

今天新学了vector容器,用法太多还不太熟。

希望能够坚持 慢慢进步吧。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值