Loading

[LeetCode] 114. Flattern 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

  1. 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。一样地,对于二叉树问题,需要考虑能不能将其分解为子问题。就本题而言,需要做以下步骤:

  1. 分别扁平化左子树和右子树

  2. 把左子树接到右子树上、右子树接在原左子树的末尾

代码如下:

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
    }
}
posted @ 2020-11-15 14:35  Zhongju.copy()  阅读(90)  评论(0编辑  收藏  举报