s-1-2

本文探讨了如何使用Python实现对二叉树、排序数组到BST、平衡二叉树等常见树形结构的操作,包括判断对称性、计算最大深度、构建BST、判断平衡、求最小深度、路径和查找等。通过实例展示了Solution类中的核心函数和递归策略。
摘要由CSDN通过智能技术生成

 101 

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        if not root:return True
        def dfs(node1, node2):
            if node1 and not node2:
                return False
            elif not node1 and node2:
                return False
            elif not node1 and not node2:
                return True
            else:
                return node1.val == node2.val and dfs(node1.left,node2.right) and dfs(node1.right,node2.left)
        return dfs(root.left,root.right)

104 

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if not root:return 0
        return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))

 108 

class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
        if not nums:
            return None
        mid = len(nums) //2 
        root = TreeNode(nums[mid])
        root.left = self.sortedArrayToBST(nums[:mid])
        root.right = self.sortedArrayToBST(nums[mid+1:])
        return root

 110 

class Solution:
    def isBalanced(self, root: TreeNode) -> bool:
        def dfs(node):
            if not node:return 0
            return 1 + max(dfs(node.left), dfs(node.right))
        if not root:return True
        return abs(dfs(root.left) - dfs(root.right)) <= 1 and self.isBalanced(root.left) and self.isBalanced(root.right)

 111 

class Solution:
    def minDepth(self, root: TreeNode) -> int:
        if not root:return 0
        if not root.left and not root.right:
            return 1
        elif not root.left and root.right:
            return 1+ self.minDepth(root.right)
        elif root.left and not root.right:
            return 1+ self.minDepth(root.left)
        else:
            return 1 + min(self.minDepth(root.left), self.minDepth(root.right))

 112 

class Solution:
    def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
        if not root:return False
        if root.val == targetSum and not root.left and not root.right:return True
        return self.hasPathSum(root.left,targetSum-root.val) or self.hasPathSum(root.right, targetSum - root.val)

118 

class Solution(object):
    def generate(self, numRows):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """
        '''
        if numRows == 0 :return []
        if numRows == 1 :return [[1]]
        pre = [1, 1]
        current = []
        for i in range(2, numRows + 1):
            current = [1]
            for j in range(i - 1):
                current.append(pre[j] + pre[j + 1])
            current.append(1)
            pre = current 
        return pre
        '''
        if numRows == 0 :return []
        if numRows == 1 :return [[1]]
        
        res = [[1],[1,1]]
        for i in range(2,numRows):
            tmp = [1]
            pre = res[-1]
            for j in range(len(pre)-1):
                tmp.append(pre[j]+pre[j+1])
            tmp.append(1)
            res.append(tmp)
        return res

119 

class Solution:
    def getRow(self, rowIndex: int) -> List[int]:
        ret = [1] * (rowIndex + 1)
        for i in range(2, rowIndex + 1):
            for j in range(i - 1, 0 ,-1):
                ret [j] += ret[j - 1]
        return ret

 121 

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if len(prices)<2: return 0 
        min_price = prices[0] 
        max_profile = 0 
        for i in prices: 
            min_price = min(min_price, i) 
            max_profile = max(max_profile, i - min_price) 
        return max_profile

 122 

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        res = 0;
        for i in range(len(prices)-1):
            if prices[i] < prices[i + 1]:
                res += prices[i + 1] - prices[i]
        return res

125 

class Solution:
    def isPalindrome(self, s: str) -> bool:
        l = []
        for i in s:
            if i.isdigit():
                l.append(i)
            elif i.isalpha():
                l.append(i.lower())
        return l == l[::-1]
        

136 

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        dic = {}
        for i in range(len(nums)):
            if nums[i] in dic:
                dic[nums[i]] += 1
            else:
                dic[nums[i]] =1
        for key,value in dic.items():
            if value ==1:
                return key

141 

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        fast = slow = head 
        while fast and fast.next: 
            fast = fast.next.next 
            slow = slow.next 
            if slow == fast: 
                return True 
        return False

 144 

class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        res = []
        def dfs(root):
            nonlocal res
            if not root:
                return
            res.append(root.val)
            dfs(root.left)
            dfs(root.right)
        dfs(root)
        return res

 145 

class Solution:
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        res = []
        def dfs(root):
            nonlocal res
            if not root:
                return
            dfs(root.left)
            dfs(root.right)
            res.append(root.val)
        dfs(root)
        return res

160 

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        p=headA
        q=headB
        if p==None or q==None:
            return None
        else:
            m=1
            n=1
            while p.next:
                m += 1
                p=p.next
            while q.next:
                n += 1
                q=q.next
            if p!=q:
                return None
            else:
                m=m-n
                if m>0:
                    h1=headA
                    h2=headB
                else:
                    h1=headB
                    h2=headA
                m=abs(m)
                while m:
                    h1=h1.next
                    m -= 1
                while h1!=h2 and h1!=None and h2!=None:
                    h1=h1.next
                    h2=h2.next
                return h1

167 

class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        nums = numbers
        start = 0
        end = len(nums) - 1
        while start < end:
            val = nums[start] + nums[end]
            if val == target:
                return [start+1,end+1]
            elif val < target:
                start += 1
            else:
                end = end-1

168 

class Solution:
    def convertToTitle(self, columnNumber: int) -> str:
        ans = []
        # 10进制 转换为 26进制,A对应1,B对应2,....Z对应26
        while columnNumber > 0:
            # 最右边位为取模运算的结果
            columnNumber -= 1
            # A的ASC码 65
            ans.append(chr(columnNumber%26 + 65))
            columnNumber //= 26
        return ''.join(ans[::-1])

169 

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) ==1:
            return nums[0]
        dict_ = {}
        for i in nums:
            if i in dict_:
                dict_[i] += 1
                if dict_[i] > len(nums)//2:
                    return i
            else:
                dict_[i] = 1
        return 0

171 

class Solution:
    def titleToNumber(self, columnTitle: str) -> int:
        ret = 0
        for i in columnTitle:
            ret = ret * 26 + ord(i) - 64
        return ret

172 

class Solution(object):
    def trailingZeroes(self, n):
        """
        :type n: int
        :rtype: int
        """
        #除过之后有多少个5 就有多少个0  比如5-1 10-2 15-3 20-4
        r = 0
        while n >= 5:
            n = n//5
            r+= n
        return r

190 

class Solution:
    # @param n, an integer
    # @return an integer
    def reverseBits(self, n):
        '''
        nums=bin(n)
        nums=nums.lstrip('0b')
        nums=nums.zfill(32)   
        #zfill 一直没找到。。。。原来是这个
        nums=nums[::-1]
        return int(nums,2)  
        
        '''
        #自己的code
        tmp = bin(n)[2:]
        tmp = tmp[::-1] + '0' * (32 - len(tmp))
        return int(tmp,2)

191 

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        r=0
        while n!=0:
            if n&1==1:
                r=r+1
            n=n/2
        return r
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值