Created
September 14, 2018 03:18
-
-
Save yokolet/cda7ca19a030b39300619568df03de23 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
| """ | |
| Description: | |
| Given a binary tree, flatten it to a linked list in-place. | |
| Example: | |
| Input: | |
| 1 | |
| / \ | |
| 2 5 | |
| /\ \ | |
| 3 4 6 | |
| Output: | |
| 1 | |
| \ | |
| 2 | |
| \ | |
| 3 | |
| \ | |
| 4 | |
| \ | |
| 5 | |
| \ | |
| 6 | |
| """ | |
| class TreeNode: | |
| def __init__(self, x): | |
| self.val = x | |
| self.left = None | |
| self.right = None | |
| def flatten(root): | |
| """ | |
| :type root: TreeNode | |
| :rtype: void Do not return anything, modify root in-place instead. | |
| """ | |
| stack = [root] | |
| prev = None | |
| while stack: | |
| cur = stack.pop() | |
| if prev: | |
| prev.right = cur | |
| prev.left = None | |
| prev = cur | |
| if cur.right: | |
| stack.append(cur.right) | |
| if cur.left: | |
| stack.append(cur.left) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment