Mid From PDF Coding C# Coding Interview

Convert a binary tree to a doubly linked list (in-order)?

public class TreeNode {
public int val;
public TreeNode left, right;
public TreeNode(int x) { val = x; }
}
TreeNode prev = null;
TreeNode head = null;

TreeNode ConvertToDLL(TreeNode root) {

if (root == null) return null;

ConvertToDLL(root.left);

if (prev == null) {
head = root; // first node becomes head

} else {

root.left = prev;

Follow on:

prev.right = root;
}
prev = root;

ConvertToDLL(root.right);

return head;
}

Explanation:

Inorder traversal connects nodes as doubly linked list by linking current with previous node.

More from C# Programming Tutorial

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details