Example: Encode N‐Ary Tree into Binary Tree - rFronteddu/general_wiki GitHub Wiki

class Node {
    int val;
    List<Node> children;

    Node(int val) {
        this.val = val;
        this.children = new ArrayList<>();
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int val) {
        this.val = val;
    }
}

class Solution {
    public TreeNode encode(Node root) {
        if (root == null) {
            return null;
        }

        TreeNode binaryRoot = new TreeNode(root.val);

        if (!root.children.isEmpty()) {
            binaryRoot.left = encode(root.children.get(0));
        }

        TreeNode current = binaryRoot.left;
        for (int i = 1; i < root.children.size(); i++) {
            current.right = encode(root.children.get(i));
            current = current.right;
        }

        return binaryRoot;
    }
}
⚠️ **GitHub.com Fallback** ⚠️