Last active
December 9, 2016 07:05
-
-
Save bittib/5620652 to your computer and use it in GitHub Desktop.
Flatten Binary Tree to Linked List. Time Complexity : O(n). Don't use extral space.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TreeNode{ | |
int val; | |
TreeNode left, right; | |
TreeNode(int val){ | |
this.val = val; | |
} | |
} | |
public void flatten(TreeNode root){ | |
root = flatten(root, null); | |
} | |
// Recurisve version | |
TreeNode flatten(TreeNode cur, TreeNode next){ | |
if (cur == null) return next; | |
next = flatten(cur.right, next); | |
next = flatten(cur.left, next); | |
cur.right = next; | |
cur.left = null; | |
return cur; | |
} | |
// Iterative version | |
public static void flattenIterative(TreeNode root){ | |
if (root == null) return; | |
Stack<TreeNode> stack = new Stack<TreeNode>(); | |
stack.push(root); | |
TreeNode prev = null; | |
while (!stack.isEmpty()){ | |
TreeNode ptr = stack.pop(); | |
if (ptr.right != null) | |
stack.push(ptr.right); | |
if (ptr.left != null) | |
stack.push(ptr.left); | |
if (prev != null){ | |
prev.right = ptr; | |
prev.left = null; | |
} | |
prev = ptr; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment