C++實(shí)現(xiàn)LeetCode(104.二叉樹的最大深度)
[LeetCode] 104. Maximum Depth of Binary Tree 二叉樹的最大深度
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 to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its depth = 3.
求二叉樹的最大深度問題用到深度優(yōu)先搜索 Depth First Search,遞歸的完美應(yīng)用,跟求二叉樹的最小深度問題原理相同,參見代碼如下:
C++ 解法一:
class Solution { public: int maxDepth(TreeNode* root) { if (!root) return 0; return 1 + max(maxDepth(root->left), maxDepth(root->right)); } };
Java 解法一:
public class Solution { public int maxDepth(TreeNode root) { return root == null ? 0 : (1 + Math.max(maxDepth(root.left), maxDepth(root.right))); } }
我們也可以使用層序遍歷二叉樹,然后計數(shù)總層數(shù),即為二叉樹的最大深度,注意 while 循環(huán)中的 for 循環(huán)的寫法有個 trick,一定要將 q.size() 放在初始化里,而不能放在判斷停止的條件中,因?yàn)閝的大小是隨時變化的,所以放停止條件中會出錯,參見代碼如下:
C++ 解法二:
class Solution { public: int maxDepth(TreeNode* root) { if (!root) return 0; int res = 0; queue<TreeNode*> q{{root}}; while (!q.empty()) { ++res; for (int i = q.size(); i > 0; --i) { TreeNode *t = q.front(); q.pop(); if (t->left) q.push(t->left); if (t->right) q.push(t->right); } } return res; } };
Java 解法二:
public class Solution { public int maxDepth(TreeNode root) { if (root == null) return 0; int res = 0; Queue<TreeNode> q = new LinkedList<>(); q.offer(root); while (!q.isEmpty()) { ++res; for (int i = q.size(); i > 0; --i) { TreeNode t = q.poll(); if (t.left != null) q.offer(t.left); if (t.right != null) q.offer(t.right); } } return res; } }
Github 同步地址:
https://github.com/grandyang/leetcode/issues/104
類似題目:
參考資料:
https://leetcode.com/problems/maximum-depth-of-binary-tree/
到此這篇關(guān)于C++實(shí)現(xiàn)LeetCode(104.二叉樹的最大深度)的文章就介紹到這了,更多相關(guān)C++實(shí)現(xiàn)二叉樹的最大深度內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- C++實(shí)現(xiàn)LeetCode(142.單鏈表中的環(huán)之二)
- C++實(shí)現(xiàn)LeetCode(143.鏈表重排序)
- C++實(shí)現(xiàn)LeetCode(109.將有序鏈表轉(zhuǎn)為二叉搜索樹)
- C++實(shí)現(xiàn)LeetCode(889.由先序和后序遍歷建立二叉樹)
- C++實(shí)現(xiàn)LeetCode(106.由中序和后序遍歷建立二叉樹)
- C++實(shí)現(xiàn)LeetCode(105.由先序和中序遍歷建立二叉樹)
- C++實(shí)現(xiàn)LeetCode(108.將有序數(shù)組轉(zhuǎn)為二叉搜索樹)
- C++實(shí)現(xiàn)LeetCode(114.將二叉樹展開成鏈表)
相關(guān)文章
C++數(shù)據(jù)結(jié)構(gòu)之實(shí)現(xiàn)鄰接表與鄰接矩陣的相互轉(zhuǎn)換
這篇文章主要為大家學(xué)習(xí)介紹了C++如何實(shí)現(xiàn)鄰接表與鄰接矩陣的相互轉(zhuǎn)換,文中的示例代碼簡潔易懂,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-07-07Qt中PaintEvent繪制實(shí)時波形圖的實(shí)現(xiàn)示例
本文主要介紹了Qt中PaintEvent繪制實(shí)時波形圖的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06VSCode插件開發(fā)全攻略之跳轉(zhuǎn)到定義、自動補(bǔ)全、懸停提示功能
這篇文章主要介紹了VSCode插件開發(fā)全攻略之跳轉(zhuǎn)到定義、自動補(bǔ)全、懸停提示,需要的朋友可以參考下2020-05-05c語言枚舉類型enum的用法及應(yīng)用實(shí)例
enum是C語言中的一個關(guān)鍵字,enum叫枚舉數(shù)據(jù)類型,枚舉數(shù)據(jù)類型描述的是一組整型值的集合,這篇文章主要給大家介紹了關(guān)于c語言枚舉類型enum用法及應(yīng)用的相關(guān)資料,需要的朋友可以參考下2021-07-07