1. 程式人生 > 實用技巧 >Leetcode 114 Flatten Binary Tree to Linked List

Leetcode 114 Flatten Binary Tree to Linked List

題目介紹

給定二叉樹,將其原地變成一個連結串列。

Example:

    1                       
   / \
  2   5     
 / \   \
3   4   6

   1
     \
      2
       \
        3
         \
          4
           \
            5
             \
              6

Solutions

直觀解法

發現連結串列的結果與先序遍歷一致,因此先進行先序遍歷,再根據遍歷的結果構造連結串列。

# 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: None Do not return anything, modify root in-place instead.
        """
        res = []
        def helpfunc(root):
            if not root:
                return
            res.append(root)
            helpfunc(root.left)
            helpfunc(root.right)
        
        helpfunc(root)
        for i in range(1, len(res)):
            res[i-1].right = res[i]
            res[i-1].left = None

逆序遍歷

逆序遍歷即按照[右子樹,左子樹,根]的方式來遍歷,所以遍歷結果為6->5->4->3->2->1,將遍歷結果逐一進行類似於連結串列反轉的操作:

class Solution(object):
    def __init__(self):
        self.prev = None
    def flatten(self, root):
        """
        :type root: TreeNode
        :rtype: None Do not return anything, modify root in-place instead.
        """
        if not root:
            return
        self.flatten(root.right)
        self.flatten(root.left)
        root.right = self.prev
        root.left = None
        self.prev = root

非遞迴解法

利用棧,先存右子樹再存左子樹,其實也是前序遍歷的非遞迴寫法。

class Solution(object):
    def flatten(self, root):
        """
        :type root: TreeNode
        :rtype: None Do not return anything, modify root in-place instead.
        """
        stack = []
        if root:
            stack.append(root)
            while stack:
                node = stack.pop()
                if node.right:
                    stack.append(node.right)
                if node.left:
                    stack.append(node.left)
                if stack:
                    node.right = stack[-1]
                    node.left = None