Created
February 15, 2015 20:43
-
-
Save dmnugent80/b63c76526f4718373ecb to your computer and use it in GitHub Desktop.
Flatten Tree In-Order
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
/** | |
* Definition for binary tree | |
* public class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode(int x) { val = x; } | |
* } | |
*/ | |
public class Solution { | |
public TreeNode lastVisited = null; | |
public void flatten(TreeNode root) { | |
flattenHelper(root); | |
} | |
public void flattenHelper(TreeNode node) { | |
if(node == null) | |
return; | |
TreeNode savedRight = node.right; | |
if(lastVisited != null) { | |
lastVisited.left = null; | |
lastVisited.right = node; | |
} | |
lastVisited = node; | |
flattenHelper(node.left); | |
flattenHelper(savedRight); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment