Title: Flatten Binary Tree to Linked List Source: leetcode.com
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 2 3 4 5 |
1 / \ 2 5 / \ \ 3 4 6 |
1 2 3 4 5 6 7 8 9 10 11 |
1 \ 2 \ 3 \ 4 \ 5 \ 6 |
Hints:
If you notice carefully in the flattened tree, each node’s right child points to the next node of a pre-order traversal.
Python solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
''' https://leetcode.com/problems/flatten-binary-tree-to-linked-list/ ''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def flatten(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ if not root: return stack = [root] while stack: node = stack.pop() if node.right: stack.append(node.right) if node.left: node.right = node.left stack.append(node.left) node.left = None if not (node.left or node.right) and stack: temp = stack.pop() node.right = temp stack.append(temp) |