详细见:leetcode.com/problems/maximum-depth-of-binary-tree
Java Solution: github
package leetcode;
/*
* 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.
*/
import tools.TreeNode辅助.TreeNode;
public class P104_MaximumDepthOfBinaryTree {
public static void main(String[] args) {
}
/*
* AC
* 0 ms
*/
static class Solution {
int max_depth = 0;
public int maxDepth(TreeNode root) {
find_max_depth(root, 0);
return max_depth;
}
private void find_max_depth(TreeNode root, int depth) {
if (root == null) {
return;
}
max_depth = Math.max(depth + 1, max_depth);
find_max_depth(root.left, depth + 1);
find_max_depth(root.right, depth + 1);
}
}
}
C Solution: github
/*
url: leetcode.com/problems/maximum-depth-of-binary-tree
AC 3ms 75.91%
*/
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
int _max(int a, int b) {
return a < b ? b : a;
}
void search(struct TreeNode* root, int cnt, int* ans) {
if (root == NULL) {
*ans = _max(cnt, *ans);
} else {
search(root->left, cnt+1, ans);
search(root->right, cnt+1, ans);
}
}
int maxDepth(struct TreeNode* root) {
int ans = 0;
search(root, 0, &ans);
return ans;
}
Python Solution: github
#coding=utf-8
'''
url: leetcode.com/problems/maximum-depth-of-binary-tree
@author: zxwtry
@email: zxwtry@qq.com
@date: 2017年4月27日
@details: Solution: 65ms 71.36%
'''
class Solution(object):
def maxDepth(self, n):
"""
:type n: TreeNode
:rtype: int
"""
if n == None: return 0
l, cnt = [n], 0
while len(l) != 0:
ll = []
for nn in l:
if nn.left != None: ll.append(nn.left)
if nn.right != None: ll.append(nn.right)
l = ll
cnt += 1
return cnt