编写程序找出二叉树中和最大的路径,二叉树结点为不等于0的整数。本题的“路径”限定为以根结点为起点,以叶结点为终点的路径。路径的和,即该路径所包含的所有结点的数据值之和。
输入格式:
输入为一组用空格间隔的整数,个数不超过100个,表示带空指针信息的二叉树先根序列。
输出格式:
输出为两行,第一行为该二叉树路径和的最大值,第二行为一组整数,每个整数后一个空格,即该最大路径包含的结点值(按从根的叶的顺序),如果存在多条满足条件路径,则输出最左边一条。
输入样例1:
1 2 0 0 3 0 0
输出样例1:
4 1 3
输入样例2:
-1 2 0 0 3 0 0
输出样例2:
2 -1 3
dfs回溯的简单应用
1.首先根据前序遍历建树。
2.通过全局变量记录当前路路径的和与最大值。
3.若和超过最大值,更新用于记录路径的res数组。
4.需要保证输出最左边,故先递归左子树,再递归右子树。
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node *left , *right;
}*BT;
int res[101];
int res_index;
int sum;
int max = -999999;
BT Create(BT root);
void dfs(BT root , int deep);
int main(){
BT root = NULL;
root = Create(root);
dfs(root , 0);
printf("%d\n",max);
for(int i = 0;i <= res_index;i ++){
printf("%d " , res[i]);
}
return 0;
}
BT Create(BT root){
int num;
scanf("%d",&num);
if(num == 0){
return NULL;
}
root = (BT)malloc(sizeof(struct Node));
root->data = num;
root->left = Create(root->left);
root->right = Create(root->right);
return root;
}
void dfs(BT root , int deep){
if(root){
sum += root->data;
if(sum > max){
max = sum;
res_index = deep;
res[deep] = root->data;
}
dfs(root->left , deep + 1);
dfs(root->right , deep + 1);
sum -= root->data;
}
}