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.
二话不说,递归求解,一次通过。
public int maxDepth(TreeNode root) {
if (root == null)
return 0;
if (root.left == null && root.right == null)
return 1;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
去借鉴借鉴别个的。
public class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left, right) + 1;
}
}
这个几乎无异。下一个。
public class Solution {
/**
* @param root: The root of binary tree.
* @return: An integer.
*/
private int depth;
public int maxDepth(TreeNode root) {
depth = 0;
helper(root, 1);
return depth;
}
private void helper(TreeNode node, int curtDepth) {
if (node == null) {
return;
}
if (curtDepth > depth) {
depth = curtDepth;
}
helper(node.left, curtDepth + 1);
helper(node.right, curtDepth + 1);
}
}