您的位置:首页 > 职场人生

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

2015-10-26 21:52 603 查看
一刷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 ¤tSum) {

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容器,用法太多还不太熟。

希望能够坚持 慢慢进步吧。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: