基于二叉链表的二叉树最长路径的求解
#include<iostream>
#include<vector>
#include<cstring>
using namespace std;
typedef struct TreeNode {
char val;
TreeNode* left;
TreeNode* right;
TreeNode() :val('0'), left(nullptr), right(nullptr) {
}
TreeNode(char x) :val(x), left(nullptr), right(nullptr) {
}
}TreeNode, * BiTree;
BiTree PreInsert() {
char x;
cin >> x;
if (x == '0') return nullptr;
TreeNode* root = new TreeNode(x);
root->left = PreInsert();
root->right = PreInsert();
return root;
}
//vector版本
void findLongestPathInBinaryTree(BiTree T, vector<char>path, vector<char>& res) {
if (T == nullptr) return;
//加入当前结点到路径中
path.push_back(T->val);
if (T->left == nullptr && T->right == nullptr) {
//如果为叶子结点
//如果当前的路径长度 大于 之前保存的最长路径
if (path.size() > res.size()) {
res = path;
}
return;
}
findLongestPathInBinaryTree(T->left, path, res);
findLongestPathInBinaryTree(T->right, path, res);
}
//数组版本
void findLongestPathInBinaryTree1(BiTree T, char path[], char* res,int n) {
if (T == nullptr) return;
//加入当前结点到路径中
path[n] = T->val;
if (T->left == nullptr && T->right == nullptr) {
//如果为叶子结点
//如果当前的路径长度 大于 之前保存的最长路径
int len = strlen(res);
if ((n + 1) > len) {
strcpy(res,path);
// res = path; //将最长数组拷贝成当前数组
res[n + 1] = '\0';
}
return;
}
findLongestPathInBinaryTree1(T->left, path, res,n+1);
findLongestPathInBinaryTree1(T->right, path, res,n+1);
}
int main() {
BiTree T;
while (true) {
T = PreInsert();
if (T == nullptr) break;
/*vector<char>v;
vector<char>res;
findLongestPathInBinaryTree(T, v, res);
cout << res.size() << endl;
for (int i = 0; i < res.size(); i++) {
cout << res[i];
}*/
char path[100] = {'\0'};
char res[100] ={'\0'};
findLongestPathInBinaryTree1(T, path, res, 0);
cout<<strlen(res)<<endl;
for(int i = 0;i<strlen(res);i++){
cout<<res[i];
}
cout<<endl;
}
return 0;
}