141. 环形链表
给定一个链表,判断链表中是否有环。
进阶:
你能否不使用额外空间解决此题?
代码如下:耗时68ms
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ if (head == None or head.next == None): return False p1 = p2 = head.next if p2.next is not None: p2 = p2.next while(p1.next is not None and p2.next is not None): if (p1 == p2): return True p1 = p1.next p2 = p2.next if p2.next is not None: p2 = p2.next return False
104. 二叉树的最大深度
给定一个链表,判断链表中是否有环。
进阶:
你能否不使用额外空间解决此题?
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回它的最大深度 3 。
代码如下:耗时44ms
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 else: left, right = 1,1 left = left + self.maxDepth(root.left) right = right + self.maxDepth(root.right) return max(left, right)互相学习,互相指教