欢迎光临
我们一直在努力

5.30华为OD机试真题 新系统 - 企业内部部门的最大层级 (Java/Py/C/C++/Js/Go)

企业内部部门的最大层级

2026 华为OD机试真题 5月30日华为OD上机新系统考试真题 100 分题型

点击查看华为 OD 机试真题完整目录:2026最新华为OD机试新系统卷 + 双机位C卷 真题题库目录|全覆盖题库 + 逐点算法考点详解

题目描述

企业的组织架构以树形结构表示,每个节点包含:

left: 左子部门(第一个子部门)

right: 右子部门(第二个子部门)

为了优化管理结构,实现扁平化管理,需要计算企业的最大管理层级深度。 请计算企业的部门层级的最大深度。

注意

1、一个部门最多能有 2 个直属的子部门(二叉树);

2、输入由数字和特殊符号#组成的序列,总结点数不超过 1024 个。数字表示该位置有子部门,#表示该位置无子部门(即无此节点)。

输入描述

输入由数字和特殊符号#组成的序列

输出描述

最大层级深度

示例1

输入

1,#,2,#,3,#,4,#,5

输出

5

说明

单链结构,深度为5

示例2

输入

1,2,3,4,5,6,7,8,9

输出

4

说明

完全二叉树,深度为4

示例3

输入

1,2,#

输出

2

说明

简单二叉树,深度为2

解题思路

本题是一个层序遍历 (BFS) 问题,将数组视为二叉树的层序遍历序列。

关键概念:

  • 输入是二叉树的层序遍历序列
  • “#” 表示该位置没有节点
  • 需要计算从根到最深叶节点的层数
  • 算法步骤

  • 初始化:将根节点深度(1)加入队列
  • 层序遍历:
    • 弹出队首节点
    • 检查左子节点:若存在,加入队列,更新最大深度
    • 检查右子节点:若存在,加入队列,更新最大深度
  • 返回结果:队列为空时返回最大深度
  • 复杂度分析

    • 时间复杂度: O(n),遍历所有节点
    • 空间复杂度: O(n),队列存储

    Java

    import java.util.*;

    public class Main {

    /**
    * 计算二叉树的最大深度
    *
    * @param nodes 二叉树层序遍历数组
    * @return 最大深度
    */

    public static int maxDepth(String[] nodes) {
    // 空树或根节点为空
    if (nodes == null || nodes.length == 0 || "#".equals(nodes[0])) {
    return 0;
    }

    // 队列中存储当前节点的深度
    Queue<Integer> queue = new LinkedList<>();
    queue.offer(1);
    int index = 1;
    int maxDepth = 1;

    // 按层序数组模拟 BFS
    while (!queue.isEmpty()) {
    int depth = queue.poll();

    // 处理左子节点
    if (index < nodes.length) {
    if (!"#".equals(nodes[index])) {
    queue.offer(depth + 1);
    maxDepth = Math.max(maxDepth, depth + 1);
    }
    index++;
    }

    // 处理右子节点
    if (index < nodes.length) {
    if (!"#".equals(nodes[index])) {
    queue.offer(depth + 1);
    maxDepth = Math.max(maxDepth, depth + 1);
    }
    index++;
    }
    }

    return maxDepth;
    }

    /**
    * 解析输入字符串
    * 格式: 1,#,2,#,3,#,4,#,5
    */

    public static String[] parseInput(String line) {
    line = line.trim();
    if (line.isEmpty()) {
    return new String[0];
    }
    return line.split(",");
    }

    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    String line = scanner.nextLine().trim();

    String[] nodes = parseInput(line);
    int result = maxDepth(nodes);
    System.out.println(result);

    scanner.close();
    }
    }

    Python

    from collections import deque
    from typing import List

    def max_depth(nodes: List[str]) > int:
    """
    计算二叉树的最大深度

    算法思路:层序遍历 (BFS)
    – 使用队列存储当前节点的深度
    – 按层序遍历数组模拟二叉树
    – 记录最大深度

    时间复杂度: O(n)
    空间复杂度: O(n)
    """
    # 空树或根节点为空
    if not nodes or nodes[0] == "#":
    return 0

    # 队列中存储当前节点的深度
    queue = deque([1])
    index = 1
    max_depth_val = 1

    # 按层序数组模拟 BFS
    while queue:
    depth = queue.popleft()

    # 处理左子节点
    if index < len(nodes):
    if nodes[index] != "#":
    queue.append(depth + 1)
    max_depth_val = max(max_depth_val, depth + 1)
    index += 1

    # 处理右子节点
    if index < len(nodes):
    if nodes[index] != "#":
    queue.append(depth + 1)
    max_depth_val = max(max_depth_val, depth + 1)
    index += 1

    return max_depth_val

    def parse_input(line: str) > List[str]:
    """解析输入: 1,#,2,#,3,#,4,#,5"""
    line = line.strip()
    if not line:
    return []
    return [x.strip() for x in line.split(',')]

    def main():
    """主函数"""
    line = input().strip()
    nodes = parse_input(line)
    result = max_depth(nodes)
    print(result)

    if __name__ == "__main__":
    main()

    JavaScript

    /**
    * 计算二叉树的最大深度
    *
    * @param {string[]} nodes – 二叉树层序遍历数组
    * @returns {number} 最大深度
    */

    function maxDepth(nodes) {
    // 空树或根节点为空
    if (!nodes || nodes.length === 0 || nodes[0] === "#") {
    return 0;
    }

    // 队列中存储当前节点的深度
    const queue = [];
    queue.push(1);
    let index = 1;
    let maxDepthVal = 1;

    // 按层序数组模拟 BFS
    while (queue.length > 0) {
    const depth = queue.shift();

    // 处理左子节点
    if (index < nodes.length) {
    if (nodes[index] !== "#") {
    queue.push(depth + 1);
    maxDepthVal = Math.max(maxDepthVal, depth + 1);
    }
    index++;
    }

    // 处理右子节点
    if (index < nodes.length) {
    if (nodes[index] !== "#") {
    queue.push(depth + 1);
    maxDepthVal = Math.max(maxDepthVal, depth + 1);
    }
    index++;
    }
    }

    return maxDepthVal;
    }

    /**
    * 解析输入字符串
    * 格式: 1,#,2,#,3,#,4,#,5
    */

    function parseInput(line) {
    line = line.trim();
    if (!line) {
    return [];
    }
    return line.split(',').map(x => x.trim());
    }

    // 主函数 – 程序入口
    const readline = require('readline');
    const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
    });

    rl.on('line', (line) => {
    const nodes = parseInput(line);
    const result = maxDepth(nodes);
    console.log(result);
    rl.close();
    });

    C++

    #include <iostream>
    #include <vector>
    #include <string>
    #include <queue>
    #include <sstream>
    #include <algorithm>
    using namespace std;

    string trim(const string& s) {
    int left = 0;
    int right = (int)s.size() 1;

    while (left <= right && s[left] == ' ') {
    left++;
    }

    while (right >= left && s[right] == ' ') {
    right;
    }

    return s.substr(left, right left + 1);
    }

    vector<string> split(const string& data) {
    vector<string> nodes;
    string item;
    stringstream ss(data);

    while (getline(ss, item, ',')) {
    nodes.push_back(trim(item));
    }

    return nodes;
    }

    int maxDepth(const vector<string>& nodes) {
    if (nodes.empty() || nodes[0] == "#") {
    return 0;
    }

    queue<int> q;
    q.push(1);

    int index = 1;
    int ans = 1;

    while (!q.empty()) {
    int depth = q.front();
    q.pop();

    if (index < (int)nodes.size()) {
    if (nodes[index] != "#") {
    q.push(depth + 1);
    ans = max(ans, depth + 1);
    }
    index++;
    }

    if (index < (int)nodes.size()) {
    if (nodes[index] != "#") {
    q.push(depth + 1);
    ans = max(ans, depth + 1);
    }
    index++;
    }
    }

    return ans;
    }

    int main() {
    string data;
    getline(cin, data);

    if (data.empty()) {
    cout << 0 << endl;
    return 0;
    }

    vector<string> nodes = split(data);
    cout << maxDepth(nodes) << endl;

    return 0;
    }

    Go

    package main

    import (
    "bufio"
    "fmt"
    "os"
    "strings"
    )

    /**
    * 计算二叉树的最大深度
    */

    func maxDepth(nodes []string) int {
    // 空树或根节点为空
    if len(nodes) == 0 || nodes[0] == "#" {
    return 0
    }

    // 使用队列存储索引和深度
    type NodeDepth struct {
    idx int
    depth int
    }

    queue := make([]NodeDepth, 0)
    queue = append(queue, NodeDepth{0, 1})
    maxDepthVal := 1

    for len(queue) > 0 {
    node := queue[0]
    queue = queue[1:]

    if node.depth > maxDepthVal {
    maxDepthVal = node.depth
    }

    // 左子节点索引
    leftIdx := 2*node.idx + 1
    if leftIdx < len(nodes) && nodes[leftIdx] != "#" {
    queue = append(queue, NodeDepth{leftIdx, node.depth + 1})
    }

    // 右子节点索引
    rightIdx := 2*node.idx + 2
    if rightIdx < len(nodes) && nodes[rightIdx] != "#" {
    queue = append(queue, NodeDepth{rightIdx, node.depth + 1})
    }
    }

    return maxDepthVal
    }

    /**
    * 解析输入字符串
    */

    func parseInput(line string) []string {
    line = strings.TrimSpace(line)
    if line == "" {
    return []string{}
    }
    parts := strings.Split(line, ",")
    result := make([]string, len(parts))
    for i, p := range parts {
    result[i] = strings.TrimSpace(p)
    }
    return result
    }

    func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Scan()
    line := scanner.Text()

    nodes := parseInput(line)
    result := maxDepth(nodes)
    fmt.Println(result)
    }

    C语言

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <ctype.h>

    #define MAX_N 1024
    #define MAX_LEN 10000

    void trim(char *s) {
    int left = 0;
    int right = strlen(s) 1;

    while (left <= right && isspace((unsigned char)s[left])) {
    left++;
    }

    while (right >= left && isspace((unsigned char)s[right])) {
    right;
    }

    int index = 0;
    for (int i = left; i <= right; i++) {
    s[index++] = s[i];
    }
    s[index] = '\\0';
    }

    int maxDepth(char nodes[][32], int n) {
    if (n == 0 || strcmp(nodes[0], "#") == 0) {
    return 0;
    }

    int queue[MAX_N];
    int front = 0;
    int rear = 0;

    queue[rear++] = 1;

    int index = 1;
    int ans = 1;

    while (front < rear) {
    int depth = queue[front++];

    if (index < n) {
    if (strcmp(nodes[index], "#") != 0) {
    queue[rear++] = depth + 1;
    if (depth + 1 > ans) {
    ans = depth + 1;
    }
    }
    index++;
    }

    if (index < n) {
    if (strcmp(nodes[index], "#") != 0) {
    queue[rear++] = depth + 1;
    if (depth + 1 > ans) {
    ans = depth + 1;
    }
    }
    index++;
    }
    }

    return ans;
    }

    int main() {
    char data[MAX_LEN];

    if (fgets(data, sizeof(data), stdin) == NULL) {
    printf("0\\n");
    return 0;
    }

    data[strcspn(data, "\\n")] = '\\0';

    if (strlen(data) == 0) {
    printf("0\\n");
    return 0;
    }

    char nodes[MAX_N][32];
    int n = 0;

    char *token = strtok(data, ",");

    while (token != NULL && n < MAX_N) {
    trim(token);
    strcpy(nodes[n++], token);
    token = strtok(NULL, ",");
    }

    printf("%d\\n", maxDepth(nodes, n));

    return 0;
    }

    完整用例

    用例1

    输入

    1,#,2,#,3,#,4,#,5

    用例2

    输入

    1,2,3,4,5,6,7,8,9

    用例3

    输入

    1,2,#

    用例4

    输入

    #

    用例5

    输入

    1,#,#

    用例6

    输入

    1,2,3,#,#,4,5

    用例7

    输入

    1,2,#,3,#,4

    用例8

    输入

    1,2,3,4,#,#,5

    用例9

    输入

    1,#,2,3,#,#

    用例10

    输入

    1,2,3,4,5,6,#,#,7

    文章目录

    • **企业内部部门的最大层级**
    • 题目描述
    • 输入描述
    • 输出描述
    • 示例1
    • 示例2
    • 示例3
    • 解题思路
        • 算法步骤
        • 复杂度分析
    • Java
    • Python
    • JavaScript
    • C++
    • Go
    • C语言
    • 完整用例
      • 用例1
      • 用例2
      • 用例3
      • 用例4
      • 用例5
      • 用例6
      • 用例7
      • 用例8
      • 用例9
      • 用例10

    在这里插入图片描述

    赞(0)
    未经允许不得转载:171主机测评 » 5.30华为OD机试真题 新系统 - 企业内部部门的最大层级 (Java/Py/C/C++/Js/Go)
    分享到: 更多 (0)

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址