LeetCode Flatten Binary Tree to Linked List

LeetCode解题之Flatten Binary Tree to Linked List

原题

把一棵二叉树变为链表,也就是一棵所有节点要么没有子节点,要么只有右节点的二叉树。

注意点:

例子:

输入:

         1
        / \        2   5
      / \   \      3   4   6

输出:

   1
    \      2
      \        3
        \          4
          \            5
            \              6

解题思路

可以看出来变化后每个节点其实都是指向了在先序遍历中的后一个节点。所以就通过栈的方式来先序遍历原树,如果一个节点有左节点,那么把它的右节点压栈(如果有的话),右指针指向原来的左节点;如果一个节点没有子节点,应该把它的右指针指向栈顶的节点。

AC源码

# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution(object):
    def flatten(self, root):
        """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """
        stack = []
        while root:
            if root.left:
                if root.right:
                    stack.append(root.right)
                root.right, root.left = root.left, None
            if not root.right and stack:
                root.right = stack.pop()
            root = root.right


if __name__ == "__main__":
    None

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。

你可能感兴趣的:(LeetCode,python,二叉树,栈,suanfa)