【LeetCode 中等題】54-二叉樹展開為連結串列
阿新 • • 發佈:2019-01-08
題目描述:給定一個二叉樹,原地將它展開為連結串列。
例如,給定二叉樹
1 / \ 2 5 / \ \ 3 4 6將其展開為:
1 \ 2 \ 3 \ 4 \ 5 \ 6
解法1。遞迴,根據題意是前序遍歷也就是根-左-右,所以撫平後應該是根-左-右,所以放到樹的遍歷中就是,把根的左給右,再把右接到左的右邊就是下面。遞迴一直到最左葉子結點的再返回到其父節點,基礎操作就是把左賦給右,再把右接到左的右下方
# 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 if root.left: self.flatten(root.left) if root.right: self.flatten(root.right) tmp = root.right root.right = root.left root.left = None while root.right: root = root.right root.right = tmp
解法2。用迴圈,基本思路是一致的,先找左子樹的最右邊的節點,在此節點下接右子樹,然後左子樹覆蓋右子樹,逐個下去,直到把所有左邊都撫平轉移到右邊。
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 cur = root while cur: if cur.left: p = cur.left while p.right: p = p.right p.right = cur.right cur.right = cur.left cur.left = None cur = cur.right