Q4.9 Find all paths which sum to a given value

来源:互联网 发布:多准数据淘宝 编辑:程序博客网 时间:2024/06/18 10:08

Q:You are given a binary tree in which each node contains a value. Design an algorithm to print all paths which sum up to that value. Note that it can be any path in the tree - it does not have to start at the root.

A:DFS.

对于当前节点,不是将其作为路径的起始点,而是将其作为路径的终点,不断向上寻找,如果找到路径的起点,则打印出路径。从根节点开始逐层判断节点是否为终点。

#include <iostream>#include <vector>#include <cmath>#include <limits.h>using namespace std;struct TreeNode {    int val;    TreeNode *left;    TreeNode *right;    TreeNode() {}    TreeNode(int x) : val(x), left(NULL), right(NULL) {}};//初始化数据 TreeNode *dfs(vector<int> &num, int start, int end) {    if (start == end) {        return NULL;    }    int mid = start + (end-start)/2;    TreeNode *root = new TreeNode(num[mid]);    root->left = dfs(num, start, mid);    root->right = dfs(num, mid+1, end);    return root;}TreeNode *sortedArrayToBST(vector<int> &num) {    const int n = num.size();    if (n == 0) {        return NULL;    }    return dfs(num,0,n);}int depth(TreeNode *root) {if (!root) {return 0;}return 1+max(depth(root->left), depth(root->right));}void print(int path[], int start, int end) {for (int i = start; i <= end; i++) {cout<<path[i]<<" ";}cout<<endl;}void findPath(TreeNode *cur, int path[], int sum, int level) {if (!cur) {return ;}path[level] = cur->val;int res = 0;for (int i = level; i >= 0; i--) {res += path[i];if (res == sum) {print(path, i, level);}}findPath(cur->left, path, sum, level+1);findPath(cur->right, path, sum, level+1);path[level] = INT_MIN;}void findPath(TreeNode *root, int sum) {const int d = depth(root);int path[d];findPath(root, path, sum, 0);}int main() {vector<int> a;for (int i = 1; i < 10; i++) {a.push_back(i);}TreeNode *root = sortedArrayToBST(a);findPath(root, 7);return 0;}


0 0