104. Maximum Depth of Binary Tree

lpy1990

代码

``````//递归
class Solution {
int maxDepth = 0;
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
helper(root, 1);
return maxDepth;
}
private void helper(TreeNode node, int cur) {
if (node == null) {
return;
}
maxDepth = Math.max(cur, maxDepth);
helper(node.left, cur + 1);
helper(node.right, cur +1);
}
}``````

代码

``````//分治
class Solution {
public int maxDepth(TreeNode root) {
int max = 0;
if (root == null) {
return max;
}

int left = maxDepth(root.left);
int right = maxDepth(root.right);

max = Math.max(left, right) + 1;
return max;
}
}``````

代码

``````//BFS
class Solution {
int maxDepth = 0;
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int depth = 0;
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i <size; i++) {
TreeNode cur = queue.poll();
if (cur.left != null) {
queue.offer(cur.left);
}
if (cur.right != null) {
queue.offer(cur.right);
}
}
depth++;
}
return depth;
}
}``````

26 声望
10 粉丝
0 条评论