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
  • 相关阅读:
    冒泡排序
    快速排序
    玩转git版本控制软件
    django内容总结
    ajax图片上传功能
    随机验证码
    制作博客系统
    django自带的用户认证和form表单功能
    COOKIE 与 SESSION
    Ajax知识
  • 原文地址:https://www.cnblogs.com/seyjs/p/11395693.html
Copyright © 2011-2022 走看看