Created
July 16, 2016 22:26
-
-
Save jianminchen/d9f18909417476f7102b5573173336ca to your computer and use it in GitHub Desktop.
flatten - Java solution - study the code written using Queue
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
/** | |
* Definition for binary tree | |
* class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode(int x) { val = x; } | |
* } | |
*/ | |
public class Solution { | |
public TreeNode flatten(TreeNode A) { | |
Queue<TreeNode> queue = new LinkedList<TreeNode>(); | |
preorder(queue, A); | |
if (queue.isEmpty()) | |
return A; | |
TreeNode node = queue.remove(); | |
TreeNode next; | |
A = node; | |
while (!queue.isEmpty()) { | |
next = queue.remove(); | |
node.left = null; | |
node.right = next; | |
next.left = null; | |
node = next; | |
} | |
return A; | |
} | |
public void preorder(Queue<TreeNode> queue, TreeNode node) { | |
if (node == null) | |
return; | |
queue.add(node); | |
preorder(queue, node.left); | |
preorder(queue, node.right); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment