[LeetCode] 114. Flattern Binary Tree to Linked List(将二叉树扁平化成单链表)
- 
Difficulty: Medium 
- 
Related Topics: Tree, Depth-first Search 
- 
Link: https://leetcode.com/problems/flatten-binary-tree-to-linked-list/ 
Description
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
    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.
Solution
题目的意思是:给定一棵二叉树,将其转换为单链表,单链表的顺序为树的前序遍历顺序,right 为单链表的 next。一样地,对于二叉树问题,需要考虑能不能将其分解为子问题。就本题而言,需要做以下步骤:
- 
分别扁平化左子树和右子树 
- 
把左子树接到右子树上、右子树接在原左子树的末尾 
代码如下:
class Solution {
    fun flatten(root: TreeNode?): Unit {
        if (root == null) {
            return
        }
        val left = root.left
        val right = root.right
        // 扁平化左右子树
        flatten(root.left)
        flatten(root.right)
        // 清除左子树
        root.left = null
        // 将左子树接在原来右子树的位置上
        root.right = left
        // 右子树则接在现在右子树的末尾
        var p = root
        while (p?.right != null) {
            p = p.right
        }
        p?.right = right
    }
}

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号