鏈接力扣104-二叉樹的最大深度
思路
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
if(root.left == null) return maxDepth(root.right) + 1;
if(root.right == null) return maxDepth(root.left) + 1;
int max = Math.max(maxDepth(root.left),maxDepth(root.right));
return max + 1;
}
}
鏈接力扣111-二叉樹的最小深度
思路文章來源:http://www.zghlxwxcb.cn/news/detail-624927.html
class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;
if(root.left == null) return minDepth(root.right) + 1;
if(root.right == null) return minDepth(root.left) +1;
int min = Math.min(minDepth(root.left),minDepth(root.right));
return min + 1;
}
}
鏈接力扣222-完全二叉樹的節(jié)點個數(shù)
思路文章來源地址http://www.zghlxwxcb.cn/news/detail-624927.html
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
return countNodes(root.left) + countNodes(root.right) + 1;
// if(root == null) return 0;
// // 層序用隊列?。。。。?/span>
// Queue<TreeNode> queue = new LinkedList<>();
// queue.offer(root);
// // 總結點個數(shù)
// int res = 0;
// while(!queue.isEmpty()){
// int size = queue.size();
// while(size-- > 0){
// TreeNode node = queue.poll();
// // 每一層的循環(huán)都用res++上
// res++;
// if(node.left != null) queue.offer(node.left);
// if(node.right != null) queue.offer(node.right);
// }
// }
// return res;
}
}
到了這里,關于【算法第十四天7.28】二叉樹的最大深度,二叉樹的最小深度 ,完全二叉樹的節(jié)點個數(shù)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!