天天看點

[LeetCode] 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.

求二叉樹的最大深度問題用到深度優先搜尋DFS,遞歸的完美應用,跟求二叉樹的最小深度問題原理相同。代碼如下:

C++ 解法一:

<a>class Solution {</a>

 Java 解法一:

我們也可以使用層序周遊二叉樹,然後計數總層數,即為二叉樹的最大深度,參見代碼如下:

C++ 解法二:

Java 解法二:

<a>public class Solution {</a>

求二叉樹的最小深度可以參見我的博文:

<a href="http://www.cnblogs.com/grandyang/p/4042168.html" target="_blank">http://www.cnblogs.com/grandyang/p/4042168.html</a>

參考資料:

<a href="https://discuss.leetcode.com/topic/10317/my-code-of-c-depth-first-search-and-breadth-first-search" target="_blank">https://discuss.leetcode.com/topic/10317/my-code-of-c-depth-first-search-and-breadth-first-search</a>

,如需轉載請自行聯系原部落客。