2026年腾讯公司技术面试题详解.docxVIP

  • 0
  • 0
  • 约4.59千字
  • 约 13页
  • 2026-01-18 发布于福建
  • 举报

第PAGE页共NUMPAGES页

2026年腾讯公司技术面试题详解

一、编程基础(3题,每题10分,共30分)

1.题目:

编写一个函数,实现二叉树的深度优先遍历(前序遍历),要求使用递归和非递归两种方式分别实现。输入为二叉树的根节点,输出为遍历结果的列表。

答案与解析:

递归实现:

python

classTreeNode:

def__init__(self,val=0,left=None,right=None):

self.val=val

self.left=left

self.right=right

defpreorder_traversal_recursive(root):

result=[]

defdfs(node):

ifnotnode:

return

result.append(node.val)

dfs(node.left)

dfs(node.right)

dfs(root)

returnresult

非递归实现:

python

defpreorder_traversal_iterative(root):

ifnotroot:

return[]

result,stack=[],[root]

whilestack:

node=stack.pop()

result.append(node.val)

ifnode.right:

stack.append(node.right)

ifnode.left:

stack.append(node.left)

returnresult

解析:

前序遍历的顺序是“根-左-右”。递归方法通过函数调用栈实现,而非递归方法使用显式栈模拟递归过程。递归简洁但可能因深度过大导致栈溢出,非递归更通用但代码稍复杂。

2.题目:

给定一个字符串,统计其中所有不同字母的频率(区分大小写),要求时间复杂度为O(n)。

答案与解析:

python

defcount_frequency(s):

freq={}

forcharins:

ifchar.isalpha():

freq[char]=freq.get(char,0)+1

returnfreq

解析:

遍历字符串一次,使用哈希表记录每个字母的出现次数。字母的统计是线性时间复杂度的典型应用。注意仅统计字母字符,忽略其他符号。

3.题目:

实现一个LRU(最近最少使用)缓存,支持`get`和`put`操作。缓存容量为固定值`capacity`。

答案与解析:

python

classLRUCache:

def__init__(self,capacity:int):

self.capacity=capacity

self.cache={}

self.order=[]

defget(self,key:int)-int:

ifkeyinself.cache:

self.order.remove(key)

self.order.append(key)

returnself.cache[key]

return-1

defput(self,key:int,value:int)-None:

ifkeyinself.cache:

self.order.remove(key)

eliflen(self.cache)=self.capacity:

oldest_key=self.order.pop(0)

delself.cache[oldest_key]

self.cache[key]=value

self.order.append(key)

解析:

LRU缓存的核心是维护一个双向顺序:`get`时将访问的元素移到队尾,`put`时若已存在则更新,若超出容量则删除最久未使用的元素。使用哈希表和列表实现,保证O(1)时间复杂度。

二、算法设计(3题,每题15分,共45分)

1.题目:

设计一个算法,找出数组中第三大的数。如果数组中少于三个不同的数,返回最大的数。

答案与解析:

python

defthird_max(nums):

first,second,third=float(-inf),float(-inf),float(-inf)

fornuminnums:

ifnumfirst:

first,second,third=num,first,second

eliffirstnumsecond:

second,third=num,second

elifsecondnumthird:

third=num

returnt

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档