zoukankan      html  css  js  c++  java
  • [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
        }
    }
    
  • 相关阅读:
    期末总结
    虚拟存储器学习记录
    实验报告
    并发编程学习记录
    进程&信号&管道实践学习记录
    异常控制流学习记录
    系统级IO实践学习记录
    系统级I/O学习记录
    Arduino小车学习与研究
    期中总结
  • 原文地址:https://www.cnblogs.com/zhongju/p/13976699.html
Copyright © 2011-2022 走看看