作者Rushia (みけねこ的鼻屎)
看板Marginalman
標題Re: [閒聊] 每日LeetCode
時間Thu Feb 16 09:20:41 2023
104. Maximum Depth of Binary Tree
給你一個二元樹,求出他的最大深度。
Example:
https://assets.leetcode.com/uploads/2020/11/26/tmp-tree.jpg
Input: root = [3,9,20,null,null,15,7]
Output: 3
思路:
1.dfs這個樹如果當前節點不為空則深度+1,並且加上左右子樹裡面比較大的深度就
是最大深度
JavaCode:
----------------------------------------
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
}
----------------------------------------
--
https://i.imgur.com/3e5CZfj.jpg
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.160.89.182 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1676510444.A.03F.html
推 a9486l: 大師 02/16 09:21
推 MurasakiSion: 大師 02/16 09:24
推 idiont: 大師 02/16 11:22
推 NTHUlagka: 大師 02/16 13:54