leetcode(Tree)–104. 二叉树的最大深度
1,题目:
2,思路:
方法一:递归:
- 找出终止条件:当前节点为空
- 找出返回值:节点为空时说明高度为0,所以返回0;节点不为空时则分别求左右子树的高度的最大值,同时加1表示当前节点的高度,返回该数值
方法二:迭代:
BFS思想:
3,代码:
方法一:递归:
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) {
return 0;
} else {
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left, right) + 1;
}
}
}
方法二:迭代:
BFS思想:
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
//BFS的层次遍历思想,记录二叉树的层数,
//遍历完,层数即为最大深度
LinkedList<TreeNode> queue = new LinkedList<>();
queue.add(root);
int maxDepth = 0;
while (!queue.isEmpty()) {
maxDepth++;
int levelSize = queue.size();
for (int i = 0; i < levelSize; i++) {
TreeNode node = queue.pollFirst();
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
}
return maxDepth;
}
}