​LeetCode刷题实战431:将 N 叉树编码为二叉树

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 将 N 叉树编码为二叉树,我们先来看题面:

https://leetcode-cn.com/problems/encode-n-ary-tree-to-binary-tree/

d7147549b3d5b85d736e9ad5e96480f7.png

设计一个算法,可以将 N 叉树编码为二叉树,并能将该二叉树解码为原 N 叉树。

一个 N 叉树是指每个节点都有不超过 N 个孩子节点的有根树。

类似地,一个二叉树是指每个节点都有不超过 2 个孩子节点的有根树。

你的编码 / 解码的算法的实现没有限制,你只需要保证一个 N 叉树可以编码为二叉树且该二叉树可以解码回原始 N 叉树即可。

36e42383814e81584c0b82a150182777.png

解题

思路 :参考官方思路,第一个子节点2接到父节点1的left,其余的兄弟节点 3,4 都接在其左边兄弟节点的right

e2a17e8a8a8d1a40592f136fc158388c.png

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 * int val;
 * TreeNode *left;
 * TreeNode *right;
 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Codec {
public:
    // Encodes an n-ary tree to a binary tree.
    TreeNode* encode(Node* root) {
        if(!root) return NULL;
        TreeNode* newroot = new TreeNode(root->val);
        TreeNode* cur = NULL;
        if(!root->children.empty())
        {
            newroot->left = encode(root->children[0]);
            cur = newroot->left;
        }
        for(int i = 1; i < root->children.size(); ++i)
        {
            cur->right = encode(root->children[i]);
            cur = cur->right;
        }
        return newroot;
    }
    
    // Decodes your binary tree to an n-ary tree.
    Node* decode(TreeNode* root) {
        if(!root) return NULL;
        Node *newroot = new Node(root->val);
        TreeNode *cur = NULL;
        if(root->left)
        {
            newroot->children.push_back(decode(root->left));
            cur = root->left;
        }
        while(cur && cur->right)
        {
            newroot->children.push_back(decode(cur->right));
            cur = cur->right;
        }
        return newroot;
    }
};

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-420题汇总,希望对你有点帮助!

LeetCode刷题实战421:数组中两个数的最大异或值

LeetCode刷题实战422:有效的单词方块

LeetCode刷题实战423:从英文中重建数字

LeetCode刷题实战424:替换后的最长重复字符

LeetCode刷题实战425:单词方块

LeetCode刷题实战426:将二叉搜索树转化为排序的双向链表

LeetCode刷题实战427:建立四叉树

LeetCode刷题实战428:序列化和反序列化 N 叉树

LeetCode刷题实战429:N 叉树的层序遍历

LeetCode刷题实战430:扁平化多级双向链表

cd8dc92088ba6e5137d58826dfac13bb.png

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值