leetcode(44)-二叉树展开为链表
给定一个二叉树,原地将它展开为一个单链表。
例如,给定二叉树
1
/ \
2 5
/ \ \
3 4 6
将其展开为:
1
\
2
\
3
\
4
\
5
\
6
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。```
我的思路,能往左走就往左走,走的时候把右子树存在栈里,走不动的时候,从栈里拿出来一个
```python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
stack = [None]
tmp = root
while True:
if tmp is None:
break
if tmp.left is not None:
if tmp.right is not None:stack.append(tmp.right)
tmp.right = tmp.left
tmp.left = None
tmp = tmp.right
elif tmp.left is None and tmp.right is not None:
tmp = tmp.right
elif tmp.left is None and tmp.right is None:
head = stack.pop()
tmp.right = head
tmp = head
将右子树接在左子树的最左子节点上,然后转换
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if not root:
return
while root:
left, left_s, right = root.left, root.left, root.right
if left:
while left.right:
left = left.right
left.right = right
root.right = left_s
root.left = None
root = root.right

浙公网安备 33010602011771号