LeetCode 114. Flatten Binary Tree to Linked List

题目

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

这道题把一棵树变成全部用right连接的一个链表,刚开始想复杂了,后来才发现其实就是最简单的想法:遍历这棵树,如果当前遍历到的节点有left,那就把left接到right下,然后把原先的right接到新的right的最右下面。刚开始快乐地写好了代码,想着while (curr.left != null)就行了,没想到还有这种情况:1.right = 2, 2.left = 3。然后看了解答发现直接while里面curr就好了,如果curr没有left就继续往右走看看还有没有带left的,如果有left就挪位置。时间复杂度,我想可能还是O(n)吧。

Runtime: 0 ms, faster than 100.00% of Java online submissions for Flatten Binary Tree to Linked List.

Memory Usage: 38.7 MB, less than 19.99% of Java online submissions for Flatten Binary Tree to Linked List.
 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public void flatten(TreeNode root) {
        TreeNode curr = root;
        while (curr != null) {
            if (curr.left == null) {
                curr = curr.right;
                continue;
            }
            TreeNode right = curr.right;
            curr.right = curr.left;
            curr.left = null;
            TreeNode temp = curr.right;
            while (temp.right != null) {
                temp = temp.right;
            }
            temp.right = right;
            curr = curr.right;
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值