zoukankan      html  css  js  c++  java
  • 【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

    解题思路:递归,从左子树开始,找到最深的左边节点,然后依次令node.right = node.left,再把原先的node.right加到原先的node.left的最右叶子节点即可。

    代码如下:

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def flatten(self, root):
            """
            :type root: TreeNode
            :rtype: void Do not return anything, modify root in-place instead.
            """
            node = root
            if node != None and node.left == None and node.right == None:
                return
            elif node != None and node.left != None:
                self.flatten(node.left)
            if node != None and node.left != None and node.right == None:
                node.right = node.left
                node.left = None
            elif node != None and node.left != None and node.right != None:
                tmpNode = node.right
                node.right = node.left
                node.left = None
                while node.right != None:
                    node = node.right
                node.right = tmpNode
                self.flatten(node.right)
            elif node != None and node.left == None and node.right != None:
                self.flatten(node.right)
            return root
  • 相关阅读:
    解决deepin没有ll等命令的办法
    解决客户端Redis中文乱码问题
    Redis 常用命令操作
    Redis常用数据类型
    Redis 入门
    Ubuntu18.04 安装netstat
    Ubuntu18.04 安装redis
    常用sql:按照表中的某一列对数据进行分组,统计数据条数
    date( ) 日期函数
    tp5 apache 转 nginx 需要配置的伪静态
  • 原文地址:https://www.cnblogs.com/seyjs/p/11395693.html
Copyright © 2011-2022 走看看