Leetcode经典面试题 – 第4周
题目来源于Leetcode
报了一个百面机器学习面试的课程
每周都有定时打卡的作业
都是常出现于面试中的题
总结在此,时常温习,
(ps:最近忙着笔试面试,更新太少)
1.递归(树)(Leetcode 110)
Given a binary tree, determine if it is height-balanced. A binary tree in which the depth of the two subtrees of every node never differ by more than 1.
给定一颗二叉树,判断高度是否平衡,高度平衡指的是所有的左右子树的高度差不大于1
思路
递归出口:
当前是空子树,返回1
递归满足条件:
1.当前左子树和右子树满足高度条件
2.左子树平衡
3.右子树平衡
class Solution(object):
def height_cal(self, r):
if not r:
return 0
else:
return 1 + max(self.height_cal(r.left), self.height_cal(r.right))
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return 1
return abs(self.height_cal(root.left) - self.height_cal(root.right)) < 2\
and self.isBalanced(root.left)\
and self.isBalanced(root.right)
2.层次遍历(树)(Leetcode 513)
Given a binary tree, find the leftmost value in the last row of the tree.
给定一颗二叉树,找到最后一行的最左的元素
思路
定义当前层数即可,BFS搜索和DFS搜索均可
class Solution(object):
def findBottomLeftValue(self, root):
pre_level = 0
d = [(root, 0)]
while d:
node, level = d.pop(0)
if level > pre_level:
res = node.val
pre_level = level
if node.left:
d.append((node.left, level+1))
if node.right:
d.append((node.right, level+1))
return res
3.前中后遍历(树)(Leetcode 144)
Given a binary tree, return the preorder traversal of its nodes’ values.
给定一颗(中序遍历的)二叉树,给出树的前序遍历
思路
迭代解法
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
d, res = [root], []
while d:
node = d.pop()
if node:
res.append(node.val)
d.append(node.right)
d.append(node.left)
return res
递归解法
class Solution(object):
def preorderTraversal(self, root):
if not root:
return []
else:
res = []
res.append(root.val)
res.extend(self.preorderTraversal(root.left))
res.extend(self.preorderTraversal(root.right))
return res
3.BST(树)(Leetcode 230)
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
给定一颗二叉搜索树,给出第k小的数
思路
二叉搜索树,每一颗小二叉树的左中右节点的大小关系依次是:左中右
中序遍历之后的整颗BST,就是递增的序列,第k-1个数满足要求
class Solution(object):
def dfs(self, r):
d = [r]
ret = []
while d:
node = d.pop(0)
ret.append(node.val)
if node.left:
d.append(node.left)
if node.right:
d.append(node.right)
return ret
def kthSmallest(self, root, k):
res = self.dfs(root)
res = sorted(res)
return res[k - 1]
4.trie(字典树,前缀树)(Leetcode 208)
Implement a trie with insert, search, and startsWith methods.
实现字典树的查找,插入,前缀操作
思路
二叉搜索树,每一颗小二叉树的左中右节点的大小关系依次是:左中右
中序遍历之后的整颗BST,就是递增的序列,第k-1个数满足要求
class Solution(object):
def dfs(self, r):
d = [r]
ret = []
while d:
node = d.pop(0)
ret.append(node.val)
if node.left:
d.append(node.left)
if node.right:
d.append(node.right)
return ret
def kthSmallest(self, root, k):
res = self.dfs(root)
res = sorted(res)
return res[k - 1]