← PayPal bank

PayPal · Question 63 · Trees

Flatten Binary Tree to Linked List

TreesJavacode⏱ O(n)💾 O(h)
Product-based

Problem

Flatten a binary tree to a linked list in-place following preorder traversal.

Approach

Recursively flatten left and right subtrees and re-link nodes.

Time O(n)Space O(h)

How it works

  1. 1Flatten both subtrees first.
  2. 2Splice the flat left between root and old right.

Sample input / output

Input:
root = [1, 2, 5, 3, 4, null, 6]
Output:
[1, 2, 3, 4, 5, 6]

Constraints

0 <= nodes <= 200; in place preorder.

Solution — read it, then walk it

Time O(n)Space O(h)Loops 3Branches 5Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE class TreeNodeDEFINE valTreeNode left, rightTreeNode(int v) { val = v;}DEFINE TreeNodebuildTree(Integer[] values)if (values.length == 0|| values[0] == null)return nullTreeNode root = newTreeNode(values[0])java.util.Queue<TreeNode> q= newjava.util.LinkedList<>()q.offer(root)DEFINE i = 1while (!q.isEmpty() &&i < values.length)TreeNode node = q.poll()if (i < values.length&& values[i] != null){ node.left = ne…i++if (i < values.length&& values[i] != null){ node.right = ne…i++RETURN rootDEFINE static voidflatten(TreeNode root)if (root == null)returnflatten(root.left)flatten(root.right)TreeNode tempRight =root.rightroot.right = root.leftroot.left = nullTreeNode current = rootwhile (current.right!= null)current = current.rightcurrent.right = tempRightDEFINE static voidmain(String[] args)TreeNode root =buildTree(new Integer[]{1,2, 5, 3, 4, null, 6})flatten(root)StringBuilder sb = newStringBuilder("[")TreeNode c = rootwhile (c != null)sb.append(c.val)c = c.rightif (c != null)sb.append(", ")System.out.println(sb.append("]").toString())END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/41

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits