8.11筆記

80. 刪除排序數組中的重複項 II

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        i = 0
        for num in nums:
            if i < 2 or num != nums[i-2]:
                nums[i] = num
                i += 1
        return i

144. 二叉樹的前序遍歷(遞歸+非遞歸)

#遞歸版本
class Solution(object):
    def preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        res = []
        self.dfs(root,res)
        return res
    def dfs(self,root,res):
        if not root:
            return 
        res.append(root.val)
        self.dfs(root.left,res)
        self.dfs(root.right,res)
#非遞歸
class Solution(object):
    def preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:
            return []
        res = []
        stack = [root]
        while stack:
            a = stack.pop()
            if a.right:
                stack.append(a.right)
            if a.left:
                stack.append(a.left)
            res.append(a.val)
        return res

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章