97. 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.
Example
Example 1:
Input: tree = {}
Output: 0
Explanation: The height of empty tree is 0.
Example 2:
Input: tree = {1,2,3,#,#,4,5}
Output: 3
Explanation: Like this:
1
/ \
2 3
/ \
4 5
注意:
Java中参数传递:(细读)
1> 基本数据类型作为参数传递时,基本类型作为参数传递时,是传递值的拷贝,无论你怎么改变这个拷贝,原值是不会改变的。
2> 对象作为参数传递时,是把对象在内存中的地址拷贝了一份传给了参数。
所以错误案例中,把基本数据类型int maxDepth作为参数,传给helper,只是拷贝了一份值给helper函数,所以无论helper里面maxDepth的值如何改变,return的值始终为1。
递归法代码(错误案例):
/**
* 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) {
if (root == null) {
return 0;
}
int maxDepth = 1;
helper(root, 1, maxDepth);
return maxDepth;
}
public void helper(TreeNode root, int curDepth, int maxDepth) {
if (root == null) {
return;
} if (root.left == null && root.right == null) {
if (curDepth > maxDepth) {
maxDepth = curDepth;
}
return;
}
helper(root.left, curDepth + 1, maxDepth);
helper(root.right, curDepth + 1, maxDepth);
}
}
递归法代码(改正):
/**
* 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
*/
int maxDepth = 1;
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
helper(root, 1);
return maxDepth;
}
public void helper(TreeNode root, int curDepth) {
if (root == null) {
return;
} if (root.left == null && root.right == null) {
if (curDepth > maxDepth) {
maxDepth = curDepth;
}
return;
}
helper(root.left, curDepth + 1);
helper(root.right, curDepth + 1);
}
}