Problem
Given a n-ary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
For example, given a 3-ary tree:
We should return its max depth, which is 3.
Note:
The depth of the tree is at most 1000.
The total number of nodes is at most 5000.
/* // Definition for a Node. class Node { public int val; public Listchildren; public Node() {} public Node(int _val,List _children) { val = _val; children = _children; } }; */ class Solution { public int maxDepth(Node root) { return helper(root); } private int helper(Node root) { if (root == null) return 0; int maxDepth = 1; for (Node node: root.children) { maxDepth = Math.max(maxDepth, 1+helper(node)); } return maxDepth; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/77378.html
摘要:題目鏈接題目分析此題和上一題思路一樣。只是不是二叉樹。思路略最終代碼若覺得本文章對你有用,歡迎用愛發(fā)電資助。 D42 559. Maximum Depth of N-ary Tree 題目鏈接 559. Maximum Depth of N-ary Tree 題目分析 此題和上一題思路一樣。只是不是二叉樹。而是正常的樹。 思路 略 最終代碼
429. N-ary Tree Level Order Traversal Given an n-ary tree, return the level order traversal of its nodes values. (ie, from left to right, level by level). For example, given a 3-ary tree:showImg(https...
摘要:題目要求對叉樹進(jìn)行水平遍歷,并輸出每一行遍歷的結(jié)果。因此無需再用隊(duì)列來額外存儲每一行的水平遍歷,可以直接通過遞歸將遍歷結(jié)果插入到相應(yīng)行的結(jié)果集中。 題目要求 Given an n-ary tree, return the level order traversal of its nodes values. (ie, from left to right, level by level)...
摘要:在線網(wǎng)站地址我的微信公眾號完整題目列表從年月日起,每天更新一題,順序從易到難,目前已更新個(gè)題。這是項(xiàng)目地址歡迎一起交流學(xué)習(xí)。 這篇文章記錄我練習(xí)的 LeetCode 題目,語言 JavaScript。 在線網(wǎng)站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公眾號: showImg(htt...
LeetCode 104 Maximum Depth of Binary Tree難度:Easy 題目描述:找到一顆二叉樹的最深深度。Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down ...
閱讀 2898·2021-09-22 15:20
閱讀 2968·2021-09-22 15:19
閱讀 3471·2021-09-22 15:15
閱讀 2406·2021-09-08 09:35
閱讀 2385·2019-08-30 15:44
閱讀 3015·2019-08-30 10:50
閱讀 3744·2019-08-29 16:25
閱讀 1596·2019-08-26 13:55