Topic:
Given a binary tree, flatten it to a linked list in-place.
Algorithm ideas:
In fact, the problem is the transformation of binary tree pre-sequence traversal
My code inherits Leetcode 144. Binary Tree Preorder Traversal
Code:
Class solution (object): def preordertraversal (self, root): "" " :type root: treenode :rtype: list[int] "" " if root == none:return [] stack = [root] result = [] while len (Stack) != 0: tmp_root = Stack.pop () if tmp_root == none:continue result.append (Tmp_ Root) &nbSp; stack.append (tmp_root.right) stack.append (Tmp_root.left) return result def flatten (self, root): "" " :type root: treenode :rtype: void do not return anything, modify root in-place instead. "" " result = self.preordertraversal (Root) for i in range (1,len (result)): result[i-1].left = None result[i-1].right = result[i]
Leetcode 114. Flatten Binary Tree to Linked List (Python edition)