马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 糖逗 于 2020-5-8 17:28 编辑
题目描述:输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
提示:
节点总数 <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
#include<iostream>
#include <malloc.h>
#include <vector>
#include <math.h>
#include <queue>
#include<vector>
using namespace std;
struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x): val(x), left(NULL), right(NULL){
}
};
TreeNode* CreateTree(vector<int> input){
TreeNode* res = (TreeNode*)malloc(sizeof(TreeNode)*input.size());
for(int i = 0; i < input.size(); i++){
res[i].val = input[i];
res[i].left = NULL;
res[i].right = NULL;
}
for(int i= 0; i < input.size(); i++){
if(2*i+1 < input.size()){
res[i].left = &res[2*i+1];
}
if(2*i+2 < input.size()){
res[i].right = &res[2*i+2];
}
}
return res;
}
void middle(TreeNode* root, vector<vector<int> >& res, int left, int right, int depth){
if(root == NULL) return;
int insert = left + (right - left) / 2;
res[depth][insert] = root->val;
middle(root->left, res, left, insert - 1, depth + 1);
middle(root->right, res, insert + 1, right, depth + 1);
}
int treeDepth(TreeNode* root){
if(root == NULL || root -> val == 0) return 0;
return max(treeDepth(root->left) + 1, treeDepth(root->right) + 1);
}
void PrintTree(TreeNode* root) {
int depth = treeDepth(root);
int width = pow(2, depth) - 1;
vector<vector<int> > res(depth, vector<int>(width, 0));
middle(root, res, 0, width - 1, 0);
for(int i = 0; i < res.size(); i++){
for(int j = 0; j < res[i].size();j++){
if(res[i][j] == 0){
cout << " ";
}
else{
cout << res[i][j];
}
}
cout << endl;
}
cout << "------------------" << endl;
}
void dfs(TreeNode* root, vector<vector<int> >& res, int sum, vector<int>& temp){
temp.push_back(root -> val);
if(sum == root -> val && !root->right && !root -> left){
res.push_back(temp);
}
if(root -> right) dfs(root -> right, res, sum - root->val, temp);
if(root -> left) dfs(root -> left, res, sum - root->val, temp);
temp.pop_back();
}
vector<vector<int> > solution(TreeNode* root, int sum){
vector<vector<int> > res;
vector<int> temp;
if(root == NULL) return res;
dfs(root, res, sum, temp);
return res;
}
int main(void){
vector<int> input1;
cout << "send numbers for the first tree" << endl;
int number1;
while(cin >> number1){
input1.push_back(number1);
}
cin.clear();
TreeNode* root = CreateTree(input1);
PrintTree(root);
int sum;
cin >> sum;
vector<vector<int> > res = solution(root, sum);
for(int i = 0; i < res.size(); i++){
for(int j = 0; j < res[0].size(); j++){
cout << res[i][j] << " ";
}
cout << endl;
}
return 0;
}
注意事项:
1.回溯法
2.本地调试后未输出多个方案,但leetcode上通过了。 |