LeetCode 431: Encode N-ary Tree to Binary Tree Solution
Master LeetCode problem 431 (Encode N-ary Tree to Binary Tree), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
431. Encode N-ary Tree to Binary Tree
Problem Explanation
Explanation:
To encode an N-ary tree to a binary tree, we can perform a recursive transformation where each node in the N-ary tree is transformed into a binary tree node. The left child of a binary tree node will represent the same node's first child in the N-ary tree, and the right child will represent the next sibling in the N-ary tree.
We can start the encoding process by visiting each node in the N-ary tree and recursively encoding its children. During this process, we need to ensure that we maintain the sibling relationships. To achieve this, we can keep track of the last child processed for each node.
Time Complexity:
The time complexity of this algorithm is O(N), where N is the total number of nodes in the N-ary tree.
Space Complexity:
The space complexity of this algorithm is O(N), considering the recursive call stack.
:
Solution Code
// Java Solution
class Solution {
public Node encode(Node root) {
if (root == null) {
return null;
}
Node binaryRoot = new Node(root.val);
if (root.children.size() > 0) {
Node firstChild = encode(root.children.get(0));
binaryRoot.left = firstChild;
Node current = firstChild;
for (int i = 1; i < root.children.size(); i++) {
current.right = encode(root.children.get(i));
current = current.right;
}
}
return binaryRoot;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 431 (Encode N-ary Tree to Binary Tree)?
This page provides optimized solutions for LeetCode problem 431 (Encode N-ary Tree to Binary Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 431 (Encode N-ary Tree to Binary Tree)?
The time complexity for LeetCode 431 (Encode N-ary Tree to Binary Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 431 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 431 in Java, C++, or Python.