LintCode: Flatten Binary Tree to Linked List

Flatten a binary tree to a fake "linked list" in pre-order traversal.
Here we use the right pointer in TreeNode as the next pointer in ListNode.

思路: 定義一個空的stack用于存儲暫時移出循環的右兒子們. 然后在root或者stack不為空的時候, 進行循環. 在循環中, 每當發現左兒子存在, 則1. 將右兒子壓入stack, 2. 將root的左兒子傳遞到右兒子, 3. 將root的左子樹設為None. 然后向右兒子進發一步; 當沒有左兒子時, 如果右兒子存在, 則向右進一步, 如果沒有, 則從stack中取出一個stand-by的節點.

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        this.val = val
        this.left, this.right = None, None
"""
class Solution:
    # @param root: a TreeNode, the root of the binary tree
    # @return: nothing
    def flatten(self, root):
        # write your code here
        stack = []
        h0 = root
        while stack or root:
            if not root:
                root = stack.pop()
            else:
                if root.left:
                    if root.right:
                        stack.append(root.right)
                    root.right = root.left
                    root.left = None
                elif root.right:
                    pass
                else:
                    if stack:
                        root.right = stack.pop()
                root = root.right
        return h0
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,769評論 0 33
  • 課程介紹 先修課:概率統計,程序設計實習,集合論與圖論 后續課:算法分析與設計,編譯原理,操作系統,數據庫概論,人...
    ShellyWhen閱讀 2,361評論 0 3
  • 樹的代碼 101. Symmetric Tree Given a binary tree, check wheth...
    lindsay_bubble閱讀 489評論 0 0
  • 94. Binary Tree Inorder Traversal 中序 inorder:左節點->根節點->右節...
    Morphiaaa閱讀 584評論 0 0
  • 姓名: 李小娜 [嵌牛導讀] :這篇文章主要介紹了Java二叉排序樹,包括二叉排序樹的定義、二叉排序樹的性質、二叉...
    n184閱讀 643評論 0 0