[leetcode]Flatten Binary Tree to Linked List @ Python


原題地址: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)為一條鏈表,而鏈表的順序為二叉樹的先序遍歷。

解題思路:首先將左右子樹分別平化為鏈表,這兩條鏈表的順序分別為左子樹的先序遍歷和右子樹的先序遍歷。然后將左子樹鏈表插入到根節點和右子樹鏈表之間,就可以了。左右子樹的平化則使用遞歸實現。

代碼:

# 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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM