2026年华为软件开发工程师面试问题及答案参考.docxVIP

  • 0
  • 0
  • 约6.14千字
  • 约 18页
  • 2026-02-09 发布于福建
  • 举报

2026年华为软件开发工程师面试问题及答案参考.docx

第PAGE页共NUMPAGES页

2026年华为软件开发工程师面试问题及答案参考

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

1.题目:

编写一个函数,实现二叉树的深度优先遍历(前序遍历),并返回遍历结果列表。假设二叉树节点定义如下:

python

classTreeNode:

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

self.val=val

self.left=left

self.right=right

示例输入:

python

构建一个示例二叉树:

1

/\

23

/\

45

root=TreeNode(1)

root.left=TreeNode(2)

root.right=TreeNode(3)

root.left.left=TreeNode(4)

root.left.right=TreeNode(5)

示例输出:`[1,2,4,5,3]`

答案与解析:

python

defpreorder_traversal(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.题目:

给定一个字符串,找出其中不重复的最长子串的长度。例如:

输入:`abcabcbb`

输出:`3`(最长不重复子串为abc)

答案与解析:

python

deflength_of_longest_substring(s):

char_set=set()

left=0

max_len=0

forrightinrange(len(s)):

whiles[right]inchar_set:

char_set.remove(s[left])

left+=1

char_set.add(s[right])

max_len=max(max_len,right-left+1)

returnmax_len

解析:

使用滑动窗口技术,`left`和`right`分别表示窗口的左右边界。当遇到重复字符时,移动`left`并移除对应字符,直到窗口内无重复字符。

3.题目:

实现一个LRU(最近最少使用)缓存,支持`get`和`put`操作。缓存容量为3。例如:

python

LRUCache=LRUCache(3)

LRUCache.put(1,1)#缓存是{1=1}

LRUCache.put(2,2)#缓存是{1=1,2=2}

LRUCache.get(1)#返回1

LRUCache.put(3,3)#去除键2

LRUCache.get(2)#返回-1(未找到)

LRUCache.put(4,4)#去除键1

LRUCache.get(1)#返回-1(未找到)

LRUCache.get(3)#返回3

LRUCache.get(4)#返回4

答案与解析:

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)

解析

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档