Last active
July 20, 2017 15:18
-
-
Save bittib/5697095 to your computer and use it in GitHub Desktop.
Flatten Binary Tree to Linked List
This file contains hidden or 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
/* | |
Given a binary tree, flatten it to a linked list in-place. | |
For example, | |
Given | |
1 | |
/ \ | |
2 5 | |
/ \ \ | |
3 4 6 | |
The flattened tree should look like: | |
1 | |
\ | |
2 | |
\ | |
3 | |
\ | |
4 | |
\ | |
5 | |
\ | |
6 | |
*/ | |
public void flatten(TreeNode root) { | |
root = flatten(root, null); | |
} | |
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 void flatten(TreeNode root){ | |
if (root == null) return; | |
TreeNode prev = null, cur = root; | |
Stack<TreeNode> stack = new Stack<TreeNode>(); | |
stack.push(cur); | |
while (!stack.isEmpty()){ | |
cur = stack.pop(); | |
if (cur.right != null) | |
stack.push(cur.right); | |
if (cur.left != null) | |
stack.push(cur.left); | |
if (prev != null){ | |
prev.right = cur; | |
prev.left = null; | |
} | |
prev = cur; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment