面试题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;
}

 
posted @ 2013-01-20 17:40  小尼人00  阅读(117)  评论(0编辑  收藏  举报