题目链接104.二叉树的最大深度
使用递归的方法
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
Deque<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int depth = 0;
while(!queue.isEmpty()){
depth++;
int size = queue.size();
for(int i=0; i<size; i++){
TreeNode node = queue.poll();
if(node.left != null){
queue.offer(node.left);
}
if(node.right != null){
queue.offer(node.right);
}
}
}
return depth;
}
}
题目链接111.二叉树的最小深度
使用递归的方法 注意与二叉树的最大深度有所区别。就是单层递归逻辑,当左子树为空时,应当返回右子树的高度;当右子树为空时,应当返回左子树的高度。
class Solution {
public int minDepth(TreeNode root) {
if(root == null){
return 0;
}
int leftDepth = minDepth(root.left);
int rightDepth = minDepth(root.right);
if(root.left == null){
return rightDepth + 1;
}
if(root.right == null){
return leftDepth +1;
}
return Math.min(leftDepth, rightDepth) + 1;
}
}
题目链接222.完全二叉树的节点数
迭代法实现
class Solution {
public int countNodes(TreeNode root) {
if(root == null){
return 0;
}
Deque<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int countNode = 0;
while(!queue.isEmpty()){
int size = queue.size();
while(size-->0){
TreeNode node = queue.poll();
countNode++;
if(node.left != null){
queue.offer(node.left);
}
if(node.right != null){
queue.offer(node.right);
}
}
}
return countNode;
}
}