Leetcode: Flatten Binary Tree to Linked List

来源:互联网 发布:c语言程序的基本单位 编辑:程序博客网 时间:2024/05/22 14:28

Question

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

For example,
Given

     1    / \   2   5  / \   \ 3   4   6

The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
click to show hints.


Solution

Analysis

Get idea from Code Ganker, hustyangiu的足迹.

When recursive function runs from top to down, it has linked the left child to root. The current root can be recorded by one global variable.

code

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def flatten(self, root):        """        :type root: TreeNode        :rtype: void Do not return anything, modify root in-place instead.        """        self.pre = None        self.helper(root)    def helper(self, root):        if root==None:            return        right = root.right        if self.pre!=None:            self.pre.left = None            self.pre.right = root        self.pre = root        self.helper(root.left )        self.helper(right)

Take home message

Get deeper understanding for currsive functions

def helper(self, root):    A    B    C    self.helper(root.left)    self.helper(root.right)

The code above implements A, B and C while code runs from top to down.

def helper(self, root):    self.helper(root.left)    self.helper(root.right)    A    B    C

The code above implements A, B and C while code runs from down to top.

For the recursive function, we can do anything from top to down or from down to top, or both of them. In general, we do things from down to top.

0 0
原创粉丝点击