LeetCode--114--二叉树展开为链表(python)
给定一个二叉树,原地将它展开为链表。
例如,给定二叉树
1
/ \
2 5
/ \ \
3 4 6
将其展开为:
1
\
2
\
3
\
4
\
5
\
6
将root的右子树放到root的左子树的最右边作为右孩子 将root的左孩子变为自己的右孩子 (root.left=None) root = root.right
1 1 1
/ \ / \ \
2 5 2 2
/ \ \ / \ / \
3 4 6 3 4 3 4
\ \
5 5
\ \
6 6
1 class Solution: 2 def flatten(self, root: TreeNode) -> None: 3 """ 4 Do not return anything, modify root in-place instead. 5 """ 6 if root==None or root.left == None and root.right == None : 7 return root 8 while(root != None): 9 if(root.left == None): 10 root = root.right 11 else: 12 pre = root.left 13 while pre and pre.right!=None: 14 pre = pre.right 15 16 pre.right = root.right 17 root.right = root.left 18 root.left = None 19 root = root.right