1. 程式人生 > >LeetCode 114. Flatten Binary Tree to Linked List

LeetCode 114. Flatten Binary Tree to Linked List

left end anything 實現 fin 後序遍歷 sel [] you

原題

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.

題目大意就是讓你將一個二叉樹轉化為一個只有右子節點的扁平樹,且每一個節點的右孩子都是他前序遍歷的下一個節點

解題思路

思路一:按照該樹的前序遍歷結果,重新構造扁平樹

思路二:循環遍歷,每次將節點的右子樹接到左子樹的最右節點下,然後再將左子樹賦值給右子樹,左子樹置為空,直到循環到最底層節點為止

思路三:正向遞歸,既然每一個節點的右孩子都是他前序遍歷的下一個節點,那麽可以采取反向後序遍歷的方式,這樣遍歷的結果和前序遍歷的值正好是互逆的。

代碼實現

思路一:

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


# 先序遍歷,然後將遍歷結果重新賦值給root
class Solution(object):
    def flatten(self, root):
        """
        :type root: TreeNode
        :rtype: void Do not return anything, modify root in-place instead.
        """
        self.POrder = []
        self.preOrder(root)
        if len(self.POrder) == 0:
            return
        del self.POrder[0]
        root.left = None
        for i in self.POrder:
            root.right = TreeNode(i)
            root = root.right
        
    def preOrder(self, node):
        if node == None:
            return 
        self.POrder.append(node.val)
        self.preOrder(node.left)
        self.preOrder(node.right)

  

思路二:

# 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.
        """
        while root:
            if root.left:
                itr = root.left
                while itr.right:
                    itr = itr.right
                itr.right = root.right
                root.left, root.right = None, root.left
            root = root.right

  

思路三:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private TreeNode prev = null;

    public void flatten(TreeNode root) {
    if (root == null)
        return;
    flatten(root.right);
    flatten(root.left);
    root.right = prev;
    root.left = null;
    prev = root;
}
}

  

LeetCode 114. Flatten Binary Tree to Linked List