首页 > 其他 > 详细

0114. Flatten Binary Tree to Linked List (M)

时间:2021-05-15 19:14:43      阅读:21      评论:0      收藏:0      [点我收藏+]

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
  }
}

0114. Flatten Binary Tree to Linked List (M)

原文:https://www.cnblogs.com/mapoos/p/14771533.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!