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

根据栈的思想,通过深度优先遍历将所有的节点退出栈中,再由栈弹出每个节点进行拼接

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)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容