LeetCode-559. N叉樹的最大深度

給定一個(gè) N 叉樹,找到其最大深度。

最大深度是指從根節(jié)點(diǎn)到最遠(yuǎn)葉子節(jié)點(diǎn)的最長(zhǎng)路徑上的節(jié)點(diǎn)總數(shù)。

例如,給定一個(gè)3叉樹:


方法一: 遞歸

算法

解決這個(gè)問題的最直觀方法就是遞歸。

此處展示了深度優(yōu)先搜索的策略。

JavaPython

class Solution {

? public int maxDepth(Node root) {

? ? if (root == null) {

? ? ? return 0;

? ? } else if (root.children.isEmpty()) {

? ? ? return 1;?

? ? } else {

? ? ? List<Integer> heights = new LinkedList<>();

? ? ? for (Node item : root.children) {

? ? ? ? heights.add(maxDepth(item));

? ? ? }

? ? ? return Collections.max(heights) + 1;

? ? }

? }

}

復(fù)雜度分析

時(shí)間復(fù)雜度:每個(gè)節(jié)點(diǎn)遍歷一次,所以時(shí)間復(fù)雜度是 O(N)O(N),其中 NN 為節(jié)點(diǎn)數(shù)。

空間復(fù)雜度:最壞情況下, 樹完全非平衡,

例如 每個(gè)節(jié)點(diǎn)有且僅有一個(gè)孩子節(jié)點(diǎn),遞歸調(diào)用會(huì)發(fā)生 NN 次(等于樹的深度),所以存儲(chǔ)調(diào)用棧需要 O(N)O(N)。

但是在最好情況下(樹完全平衡),樹的高度為 \log(N)log(N)。

所以在此情況下空間復(fù)雜度為 O(\log(N))O(log(N))。

方法二: 迭代

我們還可以在堆棧的幫助下將上面的遞歸轉(zhuǎn)換為迭代。

思路是是使用深度優(yōu)先搜索策略訪問每個(gè)節(jié)點(diǎn),同時(shí)更新每次訪問時(shí)的最大深度。

所以可以從包含根節(jié)點(diǎn)的、對(duì)應(yīng)深度為 11 的棧開始。

然后繼續(xù)迭代,從棧中彈出當(dāng)前節(jié)點(diǎn)并將子節(jié)點(diǎn)壓入棧中,每次都更新對(duì)應(yīng)深度。

JavaPython

import javafx.util.Pair;

import java.lang.Math;

class Solution {

? public int maxDepth(Node root) {

? ? Queue<Pair<Node, Integer>> stack = new LinkedList<>();

? ? if (root != null) {

? ? ? stack.add(new Pair(root, 1));

? ? }

? ? int depth = 0;

? ? while (!stack.isEmpty()) {

? ? ? Pair<Node, Integer> current = stack.poll();

? ? ? root = current.getKey();

? ? ? int current_depth = current.getValue();

? ? ? if (root != null) {

? ? ? ? depth = Math.max(depth, current_depth);

? ? ? ? for (Node c : root.children) {

? ? ? ? ? stack.add(new Pair(c, current_depth + 1));? ?

? ? ? ? }

? ? ? }

? ? }

? ? return depth;

? }

};

復(fù)雜度分析

時(shí)間復(fù)雜度:O(N)O(N)。

空間復(fù)雜度:O(N)O(N)。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Binary Tree 的遍歷,Time: O(n), Space: O(n).先序遍歷:preorder(nod...
    浩澤Hauser閱讀 592評(píng)論 0 1
  • 559 Maximum Depth of N-ary Tree N叉樹的最大深度 Description:Give...
    air_melt閱讀 240評(píng)論 0 1
  • Python語言特性 1 Python的函數(shù)參數(shù)傳遞 看兩個(gè)如下例子,分析運(yùn)行結(jié)果: 代碼一: a = 1 def...
    伊森H閱讀 3,177評(píng)論 0 15
  • 大概從走出家門那一刻開始,不管回不回頭,都有目送的眼光。 —...
    三水亭閱讀 387評(píng)論 0 0
  • 步入綠的花園 吹去層層灰衫 沐浴光 換上金色柔紗 斑駁交錯(cuò)中 兒時(shí)小小影子重現(xiàn) 攜她 采紅紅的莓 集圓圓的葉 尋啾...
    木犀草閱讀 202評(píng)論 0 4

友情鏈接更多精彩內(nèi)容