链接
牛客:二叉树的深度
LeetCode:剑指 Offer 55 - I. 二叉树的深度
104. 二叉树的最大深度
思路
有递归和非递归两种方法
代码
牛客:
public class Solution {
public int TreeDepth(TreeNode root) {
if (root == null)
return 0;
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
return left > right ? left + 1 : right + 1;
}
}
LeetCode:
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
List<TreeNode> queue = new LinkedList<>();
queue.add(root);
List<TreeNode> tmp;
int res = 0;
while (!queue.isEmpty()) {
tmp = new LinkedList<>();
for (TreeNode node : queue) {
if (node.left != null) {
tmp.add(node.left);
}
if (node.right != null) {
tmp.add(node.right);
}
}
queue = tmp;
res++;
}
return res;
}
牛客递归,LeetCode 非递归