BJFUOJ-267

本文介绍了如何使用C++编程语言,通过递归方法在基于二叉链表的二叉树中寻找最长路径。主要涉及预插入节点和在树结构中遍历的算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基于二叉链表的二叉树最长路径的求解

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值