原题网址:https://leetcode.com/problems/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.
方法:递归+深度优先搜索。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int max = 0;
private void check(TreeNode root, int depth) {
if (root == null) return;
if (root.left == null && root.right == null) {
max = Math.max(max, depth);
return;
}
if (root.left != null) check(root.left, depth+1);
if (root.right != null) check(root.right, depth+1);
}
public int maxDepth(TreeNode root) {
max = 0;
check(root, 1);
return max;
}
}