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用于存儲暫時移出循環(huán)的右兒子們. 然后在root或者stack不為空的時候, 進(jìn)行循環(huán). 在循環(huán)中, 每當(dāng)發(fā)現(xiàn)左兒子存在, 則1. 將右兒子壓入stack, 2. 將root的左兒子傳遞到右兒子, 3. 將root的左子樹設(shè)為None. 然后向右兒子進(jìn)發(fā)一步; 當(dāng)沒有左兒子時, 如果右兒子存在, 則向右進(jìn)一步, 如果沒有, 則從stack中取出一個stand-by的節(jié)點.

"""
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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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

友情鏈接更多精彩內(nèi)容