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

程序IT圈

共 2292字,需浏览 5分钟

 ·

2021-11-09 14:51

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

今天和大家聊的问题叫做 将 N 叉树编码为二叉树,我们先来看题面:
https://leetcode-cn.com/problems/encode-n-ary-tree-to-binary-tree/




设计一个算法,可以将 N 叉树编码为二叉树,并能将该二叉树解码为原 N 叉树。
一个 N 叉树是指每个节点都有不超过 N 个孩子节点的有根树。
类似地,一个二叉树是指每个节点都有不超过 2 个孩子节点的有根树。
你的编码 / 解码的算法的实现没有限制,你只需要保证一个 N 叉树可以编码为二叉树且该二叉树可以解码回原始 N 叉树即可。

解题

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




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

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector _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:扁平化多级双向链表

浏览 38
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报