AcWing 71. 二叉树的深度
原题链接
简单
作者:
实验室里刷刷题
,
2020-11-01 16:43:20
,
所有人可见
,
阅读 404
递归版本
class Solution {
public int treeDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = treeDepth(root.left);
int right = treeDepth(root.right);
return Math.max(left, right) + 1;
}
}
迭代版本(层次遍历的思想,计算层数即可)
class Solution {
public int treeDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> nodes = new LinkedList<>();
nodes.offer(root);
int depth = 0;
while (!nodes.isEmpty()) {
int curSize = nodes.size();
for (int i = 0 ; i < curSize; i++) {
TreeNode curNode = nodes.poll();
if (curNode.left != null) {
nodes.offer(curNode.left);
}
if (curNode.right != null) {
nodes.offer(curNode.right);
}
}
depth++;
}
return depth;
}
}