給定乙個二叉樹,原地將它展開為乙個單鏈表。
例如,給定二叉樹
1/ \
2 5
/ \ \
3 4 6
將其展開為:1 \
2 \3\
4\5\
6我的思路,能往左走就往左走,走的時候把右子樹存在棧裡,走不動的時候,從棧裡拿出來乙個
```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:
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
LeetCode二叉樹展開為列表
題目描述 給定乙個二叉樹,原地將它展開為乙個單鏈表。例如,給定二叉樹 1 2 5 3 4 6 將其展開為 1 2 3 4 5 6想法 總體 將所有含左子樹的結點的左子樹都移動到該結點的右指標上,原本的右子樹移動到原左子樹最右結點 這點要記得注意,一定是移動到最右結點,不然不是順序結構 實現 利用遞迴...
leetcode 二叉樹 對稱二叉樹
給定乙個二叉樹,檢查它是否是映象對稱的。例如,二叉樹 1,2,2,3,4,4,3 是對稱的。1 2 2 3 4 4 3 但是下面這個 1,2,2,null,3,null,3 則不是映象對稱的 1 2 2 3 3 方法一 遞迴 思路 如果乙個樹的左子樹與右子樹映象對稱,則該樹是對稱的 兩個樹互為映象的...
LeetCode (二叉樹)反轉二叉樹
遞迴交換每乙個節點的左右子樹,重點在於訪問每乙個節點,然後交換左右子樹 definition for a binary tree node.struct treenode struct treenode inverttree struct treenode root 由於至少要講每乙個節點都訪問一次...