Mid Coding

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