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.node

 

本身優化後的代碼:
 

反思改進策略:

            1.前序遍歷不熟悉,須要熟練編寫這個代碼app

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

相關文章
相關標籤/搜索