本文主要是介绍面试题04 - 二叉树中和为某一值的所有路径 [树],希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
先序遍历 dfs + vector (存储路径) 实现路径查找#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <vector>
#include <stack>
#include <deque>
#include <queue>
#include <bitset>
#include <list>
#include <map>
#include <set>
#include <iterator>
#include <algorithm>
#include <functional>
#include <utility>
#include <sstream>
#include <climits>
#include <cassert>
#define BUG puts("here!!!");using namespace std;
struct Node {
public :int value;Node* lchild;Node* rchild;
};
void findPath(Node* pr, int exSum, vector<int>& path, int curSum);
void findPath(Node* root, int exSum) {if(root == NULL) return;vector<int> path;int curSum = 0;findPath(root, exSum, path, curSum);
}
void findPath(Node* pr, int exSum, vector<int>& path, int curSum) {curSum += pr->value;path.push_back(pr->value);if(curSum == exSum && pr->lchild == NULL && pr->rchild == NULL) {vector<int>::iterator it = path.begin();for(; it != path.end(); ++it) {cout << *it << ' ';}cout << endl;}if(pr->lchild != NULL) {findPath(pr->lchild, exSum, path, curSum);}if(pr->rchild != NULL) {findPath(pr->rchild, exSum, path, curSum);}curSum -= pr->value;path.pop_back();
}
int main() {return 0;
}
这篇关于面试题04 - 二叉树中和为某一值的所有路径 [树]的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!