牛客网 - BM39 序列化二叉树 [Hard]

题目: https://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84?tpId=295&tqId=23455&ru=%2Fpractice%2Fe0cc33a83afe4530bcec46eba3325116&qru=%2Fta%2Fformat-top101%2Fquestion-ranking&sourceUrl=%2Fexam%2Foj

思路BFS,广度优先遍历.

CMakeLists.txt

cmake_minimum_required(VERSION 2.6)

project(bm39_seralized_tree)
set(CMAKE_CXX_STANDARD 20)
add_definitions(-g)

include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../include)
string(REPLACE ".cpp" "" file "main.cpp")
add_executable(${file}  "main.cpp")

main.cpp

#include "printer/printer.hpp"
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <vector>
#include <map>
#include <queue>
#include <numeric>
#include <set>
#include <deque>
#include <cstring>

using namespace std;

struct TreeNode {
    int val;
    TreeNode* left{nullptr};
    TreeNode* right{nullptr};
    TreeNode(int val_): val{val_} {}
};

class Solution {
    int const INF = std::numeric_limits<int>::max();
   
public:
    char* Serialize(TreeNode *root) {        
        if(!root) return "";
        stringstream ss;
        
        queue<TreeNode*> d;
        d.push(root);
        while(!d.empty()) {
            auto poll = d.front();
            d.pop();
            ss << poll->val << "_";
            // 说明不是空节点
            if(poll->val != INF) {
                d.push(poll->left ? poll->left: new TreeNode{INF});
                d.push(poll->right ? poll->right: new TreeNode{INF});
            }
        }
        
        string res = ss.str();
        char* ret = new char[res.size()];
        memcpy(ret, res.data(), res.size());
        return ret;
    }

    TreeNode* Deserialize(char *str) {
        string s{str};
        if(s == "") return nullptr;

        // 根据分割符进行分割
        stringstream ss{s};
        vector<string> strs;
        string temp;
        while(getline(ss, temp, '_')) {
            strs.push_back(temp);
        }

        int n = strs.size();
        TreeNode* root = new TreeNode{stoi(strs[0])};
        queue<TreeNode*> d;
        d.push(root);

        for(int i=1; i<n-1; i+=2) {
            auto poll = d.front();
            d.pop();

            int a = stoi(strs[i]), b = stoi(strs[i+1]);

            // 如果左节点对应的不是INF,构造真实节点
            if(a != INF) {
                poll->left = new TreeNode{a};
                d.push(poll->left);
            }

            if(b != INF) {
                poll->right = new TreeNode{b};
                d.push(poll->right);
            }
        }
        return root;
    }

    void inorder_traversal(TreeNode* root) {
        if(!root || root->val == INF) return;
        inorder_traversal(root->left);
        cout << root->val << " ";
        inorder_traversal(root->right);
    }
};

// 题目: https://www.nowcoder.com/practice/7298353c24cc42e3bd5f0e0bd3d1d759?tpId=295&tqId=1025038&ru=/exam/oj&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Foj
int main(int argc, char* argv[]) {
    /**
     * Source Tree:
     *              1
     *          2         3
     *                6      7
     */
    TreeNode root{1};
    TreeNode node1{2};
    TreeNode node2{3};
    TreeNode node3{6};
    TreeNode node4{7};

    root.left = &node1;
    root.right = &node2;
    node2.left = &node3;
    node2.right = &node4;


    Solution sol;
    auto serialized_str = sol.Serialize(&root);
    cout << serialized_str << endl;
    
    auto node = sol.Deserialize(serialized_str);

    sol.inorder_traversal(node);
    cout << endl;
    
    return EXIT_SUCCESS;
}

程序输出如下,
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值