zoukankan      html  css  js  c++  java
  • 面试题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;
    }
    

     
  • 相关阅读:
    New starting
    Ubuntu中PyCharm中字体设置
    pyshp操作shapefile
    GIS的数学基础
    向mysql中插入Date类型的数据
    mysql多字段排序
    干掉命令行窗口下MySql乱码
    JavaWeb中读取文件资源的路径问题
    Java中9种IO的读取方式
    JavaIO 将数据写入到文件中去
  • 原文地址:https://www.cnblogs.com/robbychan/p/3787172.html
Copyright © 2011-2022 走看看