Leetcode 刷题Day16----------------二叉树
1. 二叉树的最大深度 (优先掌握递归)(104)
- 题目链接:https://leetcode.cn/problems/maximum-depth-of-binary-tree/
- 文章讲解/视频讲解: https://programmercarl.com/0104.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E5%A4%A7%E6%B7%B1%E5%BA%A6.html
方法:用前序遍历计算高度--------------高度的值和深度的值相
class Solution {
public int maxDepth(TreeNode root) {
if(root==null) return 0;
int maxLeft=maxDepth(root.left);
int maxRight=maxDepth(root.right);
return Math.max(maxLeft,maxRight)+1;
}
}
类似题目:559.n叉树的最大深度
https://leetcode.cn/problems/maximum-depth-of-n-ary-tree/
class Solution {
public int maxDepth(Node root) {
if(root==null) return 0;
int max=0;
for(Node node: root.children){
int maxTemp=maxDepth(node);
max=Math.max(maxTemp,max);
}
return max+1;
}
}
2. 二叉树的最小深度(111)
- 题目链接:https://leetcode.cn/problems/minimum-depth-of-binary-tree/
- 文章讲解/视频讲解:https://programmercarl.com/0111.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E5%B0%8F%E6%B7%B1%E5%BA%A6.html
class Solution {
public int minDepth(TreeNode root) {
if(root==null) return 0;
int minLeft=minDepth(root.left);
int minRight=minDepth(root.right);
if(root.left==null) return minRight+1;
if(root.right==null) return minLeft+1;
return Math.min(minRight,minLeft)+1;
}
}
3. 完全二叉树的节点个数(222)
- 题目链接:https://leetcode.cn/problems/count-complete-tree-nodes/
- 文章讲解/视频讲解:https://programmercarl.com/0222.%E5%AE%8C%E5%85%A8%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E8%8A%82%E7%82%B9%E4%B8%AA%E6%95%B0.html
把题目当作是普通二叉树:
class Solution {
public int countNodes(TreeNode root) {
if(root==null) return 0;
int countLeft=countNodes(root.left);
int countRight=countNodes(root.right);
return countLeft+countRight+1;
}
}
把题目当作是完全二叉树:
关键是 如何判断子树是满二叉树,为了 用公式2^k -1
class Solution {
public int countNodes(TreeNode root) {
if(root==null) return 0;
int leftDepth=getDepth(root.left);
int rightDepth=getDepth(root.right);
if(leftDepth==rightDepth) {
return (1<<leftDepth)+countNodes(root.right);
}else{
return (1<<rightDepth)+countNodes(root.left);
}
}
public int getDepth(TreeNode root){
int n=0;
while(root!=null) {
root=root.left;
n++;
}
return n;
}
}