码迷,mamicode.com
首页 > 编程语言 > 详细

[leetcode]Flatten Binary Tree to Linked List @ Python

时间:2014-05-12 05:30:32      阅读:367      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   ext   

原题地址:http://oj.leetcode.com/problems/flatten-binary-tree-to-linked-list/

题意:

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
Hints:

If you notice carefully in the flattened tree, each node‘s right child points to the next node of a pre-order traversal.

由上面可以看出:这道题的意思是将一颗二叉树平化(flatten)为一条链表,而链表的顺序为二叉树的先序遍历。

解题思路:首先将左右子树分别平化为链表,这两条链表的顺序分别为左子树的先序遍历和右子树的先序遍历。然后将左子树链表插入到根节点和右子树链表之间,就可以了。左右子树的平化则使用递归实现。

代码:

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

class Solution:
    # @param root, a tree node
    # @return nothing, do it in place
    def flatten(self, root):
        if root == None:
            return
        self.flatten(root.left)
        self.flatten(root.right)
        p = root
        if p.left == None:
            return
        p = p.left
        while p.right:
            p = p.right
        p.right = root.right
        root.right = root.left
        root.left = None
bubuko.com,布布扣

 

[leetcode]Flatten Binary Tree to Linked List @ Python,布布扣,bubuko.com

[leetcode]Flatten Binary Tree to Linked List @ Python

标签:style   blog   class   code   java   ext   

原文地址:http://www.cnblogs.com/zuoyuan/p/3721157.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!