Leetcode 算法题16

653Two Sum IV - Input is a BST

给出一个二叉搜索树和一个目标数,输出是否二叉树有两个数之和为目标数

Example 1:

Input: 
    5
   / \
  3   6
 / \   \
2   4   7

Target = 9

Output: True

Example 2:

Input: 
    5
   / \
  3   6
 / \   \
2   4   7

Target = 28

Output: False
我的代码:先把所有值做个列表再进行对比

# 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 findTarget(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: bool
        """
        list_ = []
        stack = [root]
        while stack:
            node = stack.pop()
            if node:
                list_.append(node.val)
                stack.extend([node.left,node.right])
        while list_:
            num = list_.pop()
            if k - num in list_:
                return True
        return False
大神的代码

def findTarget(self, root, k):
        if not root: return False
        bfs, s = [root], set()
        for i in bfs:
            if k - i.val in s: return True
            s.add(i.val)
            if i.left: bfs.append(i.left)
            if i.right: bfs.append(i.right)
        return False

606 Construct String from Binary Tree

二叉树转为字符串

Example 1:

Input: Binary tree: [1,2,3,4]
       1
     /   \
    2     3
   /    
  4     

Output: "1(2(4))(3)"

Explanation: Originallay it needs to be "1(2(4)())(3()())",
but you need to omit all the unnecessary empty parenthesis pairs.
And it will be "1(2(4))(3)".

Example 2:

Input: Binary tree: [1,2,3,null,4]
       1
     /   \
    2     3
     \  
      4 

Output: "1(2()(4))(3)"

Explanation: Almost the same as the first example,
except we can't omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.
我的代码:

# 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 tree2str(self, t):
        """
        :type t: TreeNode
        :rtype: str
        """
        if not t:
            return ''
        if  t.right:
            return str(t.val)+'('+self.tree2str(t.left)+')'+'('+self.tree2str(t.right)+')'
        elif t.left:
            return str(t.val)+'('+self.tree2str(t.left)+')'
        else:
            return str(t.val)
        
大神的代码:十分简洁

def tree2str(self, t):
    if not t: return ''
    left = '({})'.format(self.tree2str(t.left)) if (t.left or t.right) else ''
    right = '({})'.format(self.tree2str(t.right)) if t.right else ''
    return '{}{}{}'.format(t.val, left, right)



733 Flood Fill

上色

Example 1:

Input: 
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
Explanation: 
From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected 
by a path of the same color as the starting pixel are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected
to the starting pixel.
我的代码:提交时碰到以相同颜色换相同颜色的无限循环bug,就又加了一个列表

class Solution(object):
    def floodFill(self, image, sr, sc, newColor):
        """
        :type image: List[List[int]]
        :type sr: int
        :type sc: int
        :type newColor: int
        :rtype: List[List[int]]
        """
        color = image[sr][sc]
        cordlist = [[sr,sc]]
        change = []
        while cordlist:
            i = cordlist.pop()
            if image[i[0]][i[1]] == color:
                change.append([i[0],i[1]])
                image[i[0]][i[1]] += 1
                if i[0]-1 >= 0:cordlist.append([i[0]-1,i[1]])
                if i[0]+1 < len(image):cordlist.append([i[0]+1,i[1]])
                if i[1]-1 >= 0:cordlist.append([i[0],i[1]-1])
                if i[1]+1 <len(image[0]):cordlist.append([i[0],i[1]+1])
        for cord in change:
            image[cord[0]][cord[1]] = newColor
        return image
大神的代码:对哦!一样的颜色直接不变就可以了!晕..

class Solution(object):
    def floodFill(self, image, sr, sc, newColor):
        rows, cols, orig_color = len(image), len(image[0]), image[sr][sc]
        def traverse(row, col):
            if (not (0 <= row < rows and 0 <= col < cols)) or image[row][col] != orig_color:
                return
            image[row][col] = newColor
            [traverse(row + x, col + y) for (x, y) in ((0, 1), (1, 0), (0, -1), (-1, 0))]
        if orig_color != newColor:
            traverse(sr, sc)
        return image


744 Find Smallest Letter Greater Than Target

弱智题

Examples:

Input:
letters = ["c", "f", "j"]
target = "a"
Output: "c"

Input:
letters = ["c", "f", "j"]
target = "c"
Output: "f"

Input:
letters = ["c", "f", "j"]
target = "d"
Output: "f"

Input:
letters = ["c", "f", "j"]
target = "g"
Output: "j"

Input:
letters = ["c", "f", "j"]
target = "j"
Output: "c"

Input:
letters = ["c", "f", "j"]
target = "k"
Output: "c"
class Solution(object):
    def nextGreatestLetter(self, letters, target):
        """
        :type letters: List[str]
        :type target: str
        :rtype: str
        """
        for i in letters:
            if ord(i) > ord(target):
                return i
        return letters[0]
大神的另一种方法,使用了一种不常见(或者我见识少)的函数:
bisect函数:https://www.cnblogs.com/skydesign/archive/2011/09/02/2163592.html

Using bisect:

class Solution(object):
    def nextGreatestLetter(self, letters, target):
        pos = bisect.bisect_right(letters, target)
        return letters[0] if pos == len(letters) else letters[pos]

404 Sum of Left Leaves

求一个二叉树的所有左分叶的值的和

Example:

    3
   / \
  9  20
    /  \
   15   7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
我的代码:做了个判断是否为分叶的函数

# 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 sumOfLeftLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        def Isleave(node):
            if node.left or node.right:
                return False
            else:
                return True
        ans = 0
        stack = [root]
        while stack:
            node = stack.pop()
            if node.left:
                if Isleave(node.left):
                    ans += node.left.val
                else:
                    stack.append(node.left)
            if node.right:
                stack.append(node.right)
        return ans
大神的代码:善用递归

class Solution(object):
    def sumOfLeftLeaves(self, root):
        if not root:
            return 0
        if root.left and not root.left.left and not root.left.right:
            return root.left.val + self.sumOfLeftLeaves(root.right)
        return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)




733 Flood Fill
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值