美文网首页
LintCode: Flatten Binary Tree to

LintCode: Flatten Binary Tree to

作者: 阿斯特拉 | 来源:发表于2017-04-10 07:48 被阅读0次

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

相关文章

网友评论

      本文标题:LintCode: Flatten Binary Tree to

      本文链接:https://www.haomeiwen.com/subject/zoojattx.html