Maximum Depth of Binary Tree
今天是一道有關二叉樹的題目,來自LeetCode,難度為Easy,Acceptance為46.3%。
題目如下
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.
解題思路及代碼見閱讀原文
回復0000查看更多題目
解題思路
該題較為簡單,不想做過多的解釋。
首先,看到二叉樹,應該立刻就想到二叉樹的三種遍歷方式,看看哪種方法可用。
那么,這里要求二叉樹的最大深度,很容易就可以想到前序遍歷和中序遍歷不適用,而后序遍歷是適用的。即對一個節(jié)點來說,應先求左右子樹的最大深度,然后取其中較大的一個,然后加1,即為該節(jié)點的最大深度。
最后我們來看代碼。
代碼如下
Java版
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: An integer.
*/
public int maxDepth(TreeNode root) {
// write your code here
if(null == root)
return 0;
int l = maxDepth(root.left);
int r = maxDepth(root.right);
return Math.max(l, r) + 1;
}
}
關注我
該公眾號會每天推送常見面試題,包括解題思路是代碼,希望對找工作的同學有所幫助
image