Leetcode 二叉树的路径输出

本文介绍了一种创建二叉树的方法,并提供了一个用于输出从根节点到每个叶子节点的所有路径的算法实现。通过递归的方式构建二叉树结构,并使用深度优先搜索遍历整棵树来获取路径。

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

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct binaryTreeNode
{
    int                    m_nValue;
    binaryTreeNode*        m_pLeft;
    binaryTreeNode*        m_pRight;
};
//创建二叉树的程序
void CreatBinaryTree(binaryTreeNode* &root, int data[], int i, int n)
{
    if (i <= n)
    {
        root = new binaryTreeNode;
        root->m_nValue = data[i - 1];
        CreatBinaryTree(root->m_pLeft, data, 2 * i, n);
        CreatBinaryTree(root->m_pRight, data, 2 * i + 1, n);
    }
    else
        root = nullptr;
}
void PrintTreeNode(binaryTreeNode* pNode)
{
    if (pNode != nullptr)
    {
        cout << "value of this node is" << pNode->m_nValue << endl;

        if (pNode->m_pLeft != NULL)
            cout << "value of its left child is" << pNode->m_pLeft->m_nValue << endl;
        else
            cout << "left child is null." << endl;

        if (pNode->m_pRight != NULL)
            printf("value of its right child is: %d.\n", pNode->m_pRight->m_nValue);
        else
            printf("right child is null.\n");
    }
    else
    {
        printf("this node is null.\n");
    }

    printf("\n");
}
void PrintTree(binaryTreeNode* pRoot)
{
    PrintTreeNode(pRoot);//连续的调用这个函数去显示二叉树
    if (pRoot != NULL)
    {
        if (pRoot->m_pLeft != NULL)
            PrintTree(pRoot->m_pLeft);

        if (pRoot->m_pRight != NULL)
            PrintTree(pRoot->m_pRight);
    }
}
//////////////////////////////////
////////////////////////////////
//二叉树输出路径
vector<string> TreePaths;
void DFS(binaryTreeNode* node, string answer)
{
    answer += "->" + to_string(node->m_nValue);
    if (node->m_pLeft == NULL && node->m_pRight == NULL)
        TreePaths.push_back(answer);
    else
    {
        if (node->m_pLeft!= NULL)
            DFS(node->m_pLeft, answer);
        if (node->m_pRight!= NULL)
            DFS(node->m_pRight, answer);
    }
}
vector<string> binaryTreePaths(binaryTreeNode* root) {
    if (root != NULL)
    {
        DFS(root, "");
        for (int i = 0; i < TreePaths.size(); i++)
            TreePaths[i].erase(TreePaths[i].begin(), TreePaths[i].begin() + 2);
    }
    return TreePaths;
}
//测试
int main()
{
    vector<string>result;
    binaryTreeNode* root;
    //root->mRight->mRight = nullptr;
    int data[8] = { 1,2,3,4,5,6,7,8};
    CreatBinaryTree(root, data, 1, 8);
    PrintTree(root);
    result=binaryTreePaths(root);
    for (auto c : result)
        cout << c << endl;  
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值