LeetCode 431. 将N叉树编码为二叉树 (深度优先遍历)

在这里插入图片描述

思路

在这里插入图片描述

代码实现(java)

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

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

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

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

class Codec {
    // Encodes an n-ary tree to a binary tree.
    public TreeNode encode(Node root) {
        if(root == null) {
            return null;
        }
        // 拿到头结点最为二叉树的头结点
        TreeNode head = new TreeNode(root.val);
        // 遍历多叉树孩子节点
        head.left = en(root.children);
        return head;
    }

    private TreeNode en(List<Node> children) {
        TreeNode head = null;
        TreeNode cur = null;
        // 遍历孩子节点进行连接
        for(Node child : children) {
            // 创建新的二叉树节点
            TreeNode tNode = new TreeNode(child.val);
            // 头结点为空,将第一个节点的作为首个节点(左节点)
            if(head == null) {
                head = tNode;
            } else {
                // 头结点不为空,将其余节点连接到右节点上
                cur.right = tNode;
            }
            cur = tNode;
            // 先深度优先连接每个孩子节点
            // 孩子节点连接完毕之后,才退回来连接当前节点的孩子节点
            cur.left = en(child.children);
        }
        return head;
    }

	
    // Decodes your binary tree to an n-ary tree.
    public Node decode(TreeNode root) {
        if(root == null) return null;
        // 创建头结点,将二叉树的左孩子传入,创建N叉树的孩子节点
        return new Node(root.val, de(root.left));
    }

    public List<Node> de(TreeNode root) {
        // 作为当前节点的孩子节点
        List<Node> children = new ArrayList<>();
        while(root != null) {
            // 先深度优先创建当前节点的所有的孩子节点
            // 创建完毕之后才回到当前节点进行创建
            Node cur = new Node(root.val, de(root.left));
            children.add(cur);
            root = root.right;
        }
        return children;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(root));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值