0114. Flatten Binary Tree to Linked List (M)

Flatten Binary Tree to Linked List (M)

题目

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

题意

将一个二叉树的结构变为只有右子树的一直链,且顺序为原二叉树的前序遍历。

思路

方法有点像 Morris Traversal:如果当前结点root存在左子树,则将该结点的右子树接在其左子树最右结点的右边,再将root的左子树变为右子树,令 root = root.right 重复上述操作。


代码实现

Java

class Solution {
    public void flatten(TreeNode root) {
        while (root != null) {
            if (root.left != null) {
                TreeNode x = root.left;
                while (x.right != null) {
                    x = x.right;
                }
                x.right = root.right;
                root.right = root.left;
                root.left = null;
            }
            root = root.right;
        }
    }
}

JavaScript

/**
 * @param {TreeNode} root
 * @return {void} Do not return anything, modify root in-place instead.
 */
var flatten = function (root) {
  while (root) {
    if (root.left) {
      let tmp = root.left
      while (tmp.right) tmp = tmp.right
      tmp.right = root.right
      root.right = root.left
      root.left = null
    }
    root = root.right
  }
}
posted @ 2021-05-15 14:40  墨云黑  阅读(30)  评论(0编辑  收藏  举报