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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值