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
  • 相关阅读:
    三极管8050和8550对管的参数
    三极管9014 管脚
    水深不语,人稳不言
    编译结果分析
    三母运算符
    C语言关键词解释
    51定时器初值的计算
    聪明人都在远离手机虚假繁荣的“人脉”关系
    每段路,都是一种领悟
    你的灯亮着吗读后感二
  • 原文地址:https://www.cnblogs.com/seyjs/p/11395693.html
Copyright © 2011-2022 走看看