Binary Tree to DLL
Binary Tree to DLL is a hard trees & bst problem solved with the tree to lists and vice-versa pattern.
The best approach, optimal (inorder with a prev pointer), runs in O(n) time and O(h) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from collect nodes, then link up.
Problem
Convert a binary tree in place into a doubly linked list that follows the tree’s inorder order. Reuse each node’s left pointer as prev and its right pointer as next, and return the head of the list. (GFG names the class Node; here we use TreeNode.)
Examples
Example 1
- Input
root = [10, 12, 15, 25, 30, 36]- Output
25 <-> 12 <-> 30 <-> 10 <-> 36 <-> 15- Why
- The list follows inorder order.
Example 2
- Input
root = [1, 3, 2]- Output
3 <-> 1 <-> 2
Constraints
- The tree has
1to10^5nodes. - Do it in place: left becomes prev and right becomes next.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 4 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Collect nodes, then link | O(n) | O(n) |
| Optimal (inorder with a prev pointer) | O(n) | O(h) |
1Collect nodes, then link
O(n)O(n)Store the nodes in inorder order in a list, then link neighbours.
- Inorder into a list.
- For i: list[i].left = list[i - 1]; list[i].right = list[i + 1].
class Solution {
TreeNode bToDLL(TreeNode root) {
List<TreeNode> nodes = new ArrayList<>();
inorder(root, nodes);
for (int i = 0; i < nodes.size(); i++) {
nodes.get(i).left = i > 0 ? nodes.get(i - 1) : null;
nodes.get(i).right = i + 1 < nodes.size() ? nodes.get(i + 1) : null;
}
return nodes.get(0);
}
private void inorder(TreeNode n, List<TreeNode> out) {
if (n == null) return;
inorder(n.left, out);
out.add(n);
inorder(n.right, out);
}
}class Solution:
def bToDLL(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
nodes: List[TreeNode] = []
self.inorder(root, nodes)
for i in range(len(nodes)):
nodes[i].left = nodes[i - 1] if i > 0 else None
nodes[i].right = nodes[i + 1] if i + 1 < len(nodes) else None
return nodes[0]
def inorder(self, n: Optional[TreeNode], out: List[TreeNode]) -> None:
if n is None:
return
self.inorder(n.left, out)
out.append(n)
self.inorder(n.right, out)class Solution {
public:
TreeNode* bToDLL(TreeNode* root) {
vector<TreeNode*> nodes;
inorder(root, nodes);
for (size_t i = 0; i < nodes.size(); i++) {
nodes[i]->left = i > 0 ? nodes[i - 1] : nullptr;
nodes[i]->right = i + 1 < nodes.size() ? nodes[i + 1] : nullptr;
}
return nodes[0];
}
private:
void inorder(TreeNode* n, vector<TreeNode*>& out) {
if (n == nullptr) return;
inorder(n->left, out);
out.push_back(n);
inorder(n->right, out);
}
};function bToDLL(root) {
const nodes = [];
inorder(root, nodes);
for (let i = 0; i < nodes.length; i++) {
nodes[i].left = i > 0 ? nodes[i - 1] : null;
nodes[i].right = i + 1 < nodes.length ? nodes[i + 1] : null;
}
return nodes[0];
}
function inorder(n, out) {
if (n === null) return;
inorder(n.left, out);
out.push(n);
inorder(n.right, out);
}2Optimal (inorder with a prev pointer)
O(n)O(h)Recursion only; the tree's own pointers become the list.Traverse inorder, keeping the previously visited node. Link it to the current one as you go. The first visited node is the head.
- go(left).
- If prev is null, head = cur; else prev.right = cur, cur.left = prev. prev = cur.
- go(right).
class Solution {
private TreeNode head, prev;
TreeNode bToDLL(TreeNode root) {
head = prev = null;
convert(root);
return head;
}
private void convert(TreeNode cur) {
if (cur == null) return;
convert(cur.left);
if (prev == null) head = cur;
else { prev.right = cur; cur.left = prev; }
prev = cur;
convert(cur.right);
}
}class Solution:
def bToDLL(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
self.head = self.prev = None
self.convert(root)
return self.head
def convert(self, cur: Optional[TreeNode]) -> None:
if cur is None:
return
self.convert(cur.left)
if self.prev is None:
self.head = cur
else:
self.prev.right = cur
cur.left = self.prev
self.prev = cur
self.convert(cur.right)class Solution {
private:
TreeNode *head, *prev;
public:
TreeNode* bToDLL(TreeNode* root) {
head = prev = nullptr;
convert(root);
return head;
}
private:
void convert(TreeNode* cur) {
if (cur == nullptr) return;
convert(cur->left);
if (prev == nullptr) head = cur;
else { prev->right = cur; cur->left = prev; }
prev = cur;
convert(cur->right);
}
};function bToDLL(root) {
let head = null, prev = null;
function convert(cur) {
if (cur === null) return;
convert(cur.left);
if (prev === null) head = cur;
else { prev.right = cur; cur.left = prev; }
prev = cur;
convert(cur.right);
}
convert(root);
return head;
}Edge cases to test
- Single node
- Skewed tree
Hints
Hint 1
Do an inorder traversal while remembering the previously visited node. Link prev.right = cur and cur.left = prev.
FAQ
What is the best time complexity for Binary Tree to DLL?
Optimal (inorder with a prev pointer) runs in O(n) time and O(h) extra space.
Which pattern does Binary Tree to DLL use?
It is a trees & bst problem that uses the tree to lists and vice-versa pattern. Other problems with the same pattern: Flatten Binary Tree to Linked List.
Is there a brute force solution for Binary Tree to DLL?
Yes. Collect nodes, then link takes O(n) time and O(n) space. Store the nodes in inorder order in a list, then link neighbours.
Which edge cases should I test for Binary Tree to DLL?
Single node; Skewed tree.