【算法之路】✌ 吃透对称性递归 (五)

248 阅读3分钟

Offer 驾到,掘友接招!我正在参与2022春招系列活动-刷题打卡任务,点击查看活动详情

前言

数据结构与算法属于开发人员的内功,不管前端技术怎么变,框架怎么更新,版本怎么迭代,它终究是不变的内容。 始终记得在参加字节青训营的时候,月影老师说过的一句话,不要问前端学不学算法。计算机学科的每一位都有必要了解算法,有写出高质量代码的潜意识

一、N叉树的最大深度

1.1 问题描述

给定一个 N 叉树,找到其最大深度。

最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。

N 叉树输入按层序遍历序列化表示,每组子节点由空值分隔(请参见示例)。

示例 1:

输入:root = [1,null,3,2,4,null,5,6]
输出:3

示例 2:

输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
输出:5

1.2 实现思路 + AC代码

先简单看一下关于N叉树题目给的定义吧;

 * // Definition for a Node.
 * function Node(val,children) {
 *    this.val = val;
 *    this.children = children;
 * };
 */

思路一:深度优先遍历

递归求出每个子树的最大深度。

var maxDepth = function(root) {
    let max = -1
    const rec = (root,index)=>{
        if(!root) return
        max = Math.max(max,index)
        for(const child of root.children){
            rec(child,index+1)
        }
    }
    rec(root,0)
    return max==-1? 0 : max+1
};

二、N叉树的前序遍历

2.1 问题描述

给定一个 n 叉树的根节点  root ,返回 其节点值的 前序遍历 。

n 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)。

示例 1:

输入: root = [1,null,3,2,4,null,5,6]
输出: [1,3,5,6,2,4]

示例 2:

输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
输出:[1,2,3,6,7,11,14,4,8,12,5,9,13,10]

2.2 题解分析

注意好前序遍历的几个要点这个问题就非常简单

  • 先访问当前节点
  • 在访问当前节点的左子节点
  • 最后访问当前节点的右子节点
  • 递归重复上述步骤

2.3 AC代码

/**
 * // Definition for a Node.
 * function Node(val, children) {
 *    this.val = val;
 *    this.children = children;
 * };
 */

var preorder = function(root) {
    const res = []
    const rec = (root)=>{
        if(!root) return
        res.push(root.val)
        for(const child of root.children){
            rec(child)
        }
    }
    rec(root)
    return res
};

总结

对称性质的算法一共有六个系列

好了,本篇 【算法之路】✌ 吃透对称性递归 (五)到这里就结束了,我是邵小白,一个在前端领域摸爬滚打的大三学生,欢迎👍评论。