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 {
int depth = 1;
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
int leftDepth = depth;
int rightDepth = depth;
if(root.left != null){
depth++;
leftDepth = maxDepth(root.left);
depth--;
}
if(root.right !=null){
depth++;
rightDepth = maxDepth(root.right);
depth--;
}
return rightDepth > leftDepth ? rightDepth:leftDepth;
}
}
时间复杂度O(n), 空间复杂度O(1)。
看了看论坛,大牛真是神一样的存在。看看代码如下:
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
return 1+Math.max(maxDepth(root.left),maxDepth(root.right));
}