/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int depth = 0, maxDepth = 0;
public void dfs(TreeNode root) {
if (root == null) {
return;
}
depth++;
if (depth > maxDepth) {
maxDepth = depth;
}
dfs(root.left);
dfs(root.right);
depth--;
}
public int maxDepth(TreeNode root) {
if (root == null) {
return depth;
}
dfs(root);
return maxDepth;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
层序:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
int res = 0;
while (!queue.isEmpty()) {
Queue<TreeNode> temp = new LinkedList<TreeNode>();
for (TreeNode node : queue) {
if (node.left != null) {
temp.offer(node.left);
}
if (node.right != null) {
temp.offer(node.right);
}
}
queue = temp;
res++;
}
return res;
}
}