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; }
* }
*/
class Solution {
int max = 0;
public void dfs(TreeNode n,int depth)
{
if(n==null) return;
max = Math.max(max,depth);
dfs(n.left,depth+1);
dfs(n.right,depth+1);
}
public int maxDepth(TreeNode root) {
if(root == null) return 0;
dfs(root,1);
return max;
}
}