leetcode-python 第十三周

1. Implement Queue Using Stacks [59ms]

# 方法1:两个栈实现队列
class Queue(object):
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack = []


    def push(self, x):
        """
        :type x: int
        :rtype: nothing
        """
        self.stack.append(x)

    def pop(self):
        """
        :rtype: nothing
        """
        if self.empty(): return None

        tmp = []
        while not self.empty():
            tmp.append(self.stack.pop())
        val = tmp.pop()
        while len(tmp) != 0:
            self.stack.append(tmp.pop())

    def peek(self):
        """
        :rtype: int
        """
        if not self.empty():
            return self.stack[0]
        else:
            return None

    def empty(self):
        """
        :rtype: bool
        """
        return True if len(self.stack) == 0 else False

2. Binary Path Tree [49ms]

class Solution:
    # @param {TreeNode} root
    # @return {string[]}
    import copy
    def binaryTreePaths(self, root):
        if root == None:
            return []
        ans = []
        self.goDown(root, [], ans)
        for i in range(len(ans)):
            ans[i] = "->".join(ans[i])
        return ans

    def goDown(self, node, a, ans):
        if node.left == None and node.right == None:
            a.append(str(node.val))
            tmp = copy.copy(a)
            ans.append(tmp)
            return
        a.append(str(node.val))
        if node.left != None: 
            self.goDown(node.left, a, ans)
            a.pop()
        if node.right != None: 
            self.goDown(node.right, a, ans)
            a.pop()
        return

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None   

3. Valid Parentheses [49ms]

# 方法1:使用栈
class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        left = {"(":0, "{":1, "[":2}
        right = {")":0, "}":1, "]":2}
        stack = []
        i = 0
        while i < len(s):
            if s[i] in left:
                stack.append(s[i])
            else:
                if len(stack) != 0:
                    l = stack.pop()
                    if left[l] != right[s[i]]:
                        return False
                else:
                    return False
            i += 1
        if len(stack) != 0: return False
        return True

4. Path Sum [89ms]

# 方法1:要判断是不是叶节点
class Solution(object):
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        if root == None:
            return False
        ans = self.goDown(root, 0, sum)
        return ans

    def goDown(self, node, tmp, sum):
        if node == None:
            return False
        tmp2 = tmp + node.val
        if node.left or node.right:
            return self.goDown(node.left, tmp2, sum) or self.goDown(node.right, tmp2, sum)
        else:
            return tmp2 == sum
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

5. Validate Binary Tree [59ms]

# 方法1:中序遍历 [72ms]
# 方法2:上下边界 [59ms]
class Solution(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if root == None:
            return True

        inord = []
        self.inorder(root, inord)
        if len(inord) == 1:
            return True
        i = 0
        while i + 1 < len(inord):
            if inord[i] >= inord[i+1]:
                return False
            i += 1
        if inord[-1] <= inord[-2]:
            return False
        return True

    def inorder(self, node, inord):
        if node == None:
            return 

        self.inorder(node.left, inord)
        inord.append(node.val)
        self.inorder(node.right, inord)

# 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 isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        return self.valid(root, -2147483649, 2147483649)

    def valid(self, node, minval, maxval):
        if node == None:
            return True
        if minval < node.val < maxval:
            return (self.valid(node.left, minval, node.val)) and (self.valid(node.right, node.val, maxval))
        else:
            return False

6. Same Tree [32ms]

# 方法1:递归
class Solution(object):
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        if q == None and p == None:
            return True
        elif q != None and p != None:
            if q.val == p.val:
                left = self.isSameTree(p.left, q.left)
                right = self.isSameTree(p.right, q.right)
                return (left and right)
            else:
                return False
        else:
            return False
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

7. Implement Stack Using Queues [56ms]

# 方法1:队列每次取值前都翻动自己一次模拟栈
class Stack(object):
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.queue = []

    def push(self, x):
        """
        :type x: int
        :rtype: nothing
        """
        self.queue.insert(0, x)


    def pop(self):
        """
        :rtype: nothing
        """
        if self.empty():
            return
        lth = len(self.queue) - 1
        while lth:
            self.queue.insert(0, self.queue.pop())
            lth -= 1
        self.queue.pop()

    def top(self):
        """
        :rtype: int
        """
        if self.empty():
            return None
        else:
            return self.queue[0]

    def empty(self):
        """
        :rtype: bool
        """
        if len(self.queue) == 0:
            return True
        else:
            return False
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值