zoukankan      html  css  js  c++  java
  • 897. Increasing Order Search Tree

    题目来源:  
     https://leetcode.com/problems/increasing-order-search-tree/
    自我感觉难度/真实难度:medium/easy
    题意:
     
    分析:
     
    自己的代码:
     
    优秀代码:
     
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def increasingBST(self, root):
            """
            :type root: TreeNode
            :rtype: TreeNode
            """
            array=self.inOrder(root)
            if not array:
                return 
            newRoot=TreeNode(array[0])
            curr=newRoot
            for i in range(1,len(array)):
                curr.right=TreeNode(array[i])
                curr=curr.right
            return newRoot
        
        
        def inOrder(self,root):
            
            
            if not root:
                return []
            res=[]
            res.extend(self.inOrder(root.left))
            res.append(root.val)
            res.extend(self.inOrder(root.right))
            return res

    代码效率/结果:
            Runtime: 200 ms, faster than 45.33% of Python3 online submissions forIncreasing Order Search Tree.
    class Solution:
      def increasingBST(self, root):
        dummy = TreeNode(0)
        self.prev = dummy
        def inorder(root):
          if not root: return None
          inorder(root.left)
          root.left = None
          self.prev.right = root
          self.prev = root
          inorder(root.right)
        inorder(root)
        return dummy.right

          Runtime: 160 ms, faster than 63.16% of Python3 online submissions forIncreasing Order Search Tree.

    自己优化后的代码:
     

    反思改进策略:

                1.前序遍历不熟悉,需要熟练编写这个代码

        2.看不懂优化的第二个解答: .prev     TreeNode(0)

  • 相关阅读:
    find 查找练习
    shell脚本基础练习
    新增ceph节点报错
    正则表达式作业练习
    3.Linux文件管理和IO重定向
    2.Linux入门和帮助
    作业练习
    1.安装虚拟机和Linux操作系统
    “MVC+Nhibernate+Jquery-EasyUI”信息发布系统 第二篇(数据库结构、登录窗口、以及主界面)
    redis数据结构-布隆过滤器
  • 原文地址:https://www.cnblogs.com/captain-dl/p/10165865.html
Copyright © 2011-2022 走看看