114. Flatten Binary Tree to Linked List-Python-LeetCode

114. Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

For example, given the following tree:

    1
   / \
  2   5
 / \   \
3   4   6

The flattened tree should look like:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

First

根據(jù)棧的思想,通過深度優(yōu)先遍歷將所有的節(jié)點(diǎn)退出棧中,再由棧彈出每個節(jié)點(diǎn)進(jìn)行拼接

from quixote.structs.tree import TreeNode

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

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

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

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