leetcode-104. 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 dep = 0;
public int maxDepth(TreeNode root) {
helper(root,1);
return dep;
}
private void helper(TreeNode root, int i){
if(root ==null) return ;
dep = Math.max(dep,i);
helper(root.left,i+1);
helper(root.right,i+1);
}
}