一. 学习文章及资料
二. 学习内容
方法一:后序遍历
根节点的高度就是二叉树的最大深度,通过后序求的根节点高度来求的二叉树最大深度。
class Solution {
public int maxDepth(TreeNode root) {
if(root==null) return 0;
int leftdepth=maxDepth(root.left);
int rightdepth=maxDepth(root.right);
int depth=Math.max(leftdepth,rightdepth)+1;
return depth;
}
}
方法二:层序遍历
class Solution {
public int maxDepth(TreeNode root) {
Queue<TreeNode> queue=new LinkedList<>();
int depth=0;
if(root!=null) queue.offer(root);
while(!queue.isEmpty()){
int size=queue.size();
depth++;
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;
}
}
方法一:后序遍历
根节点到叶子节点的最小距离,就是求高度的过程,不过这个最小距离也同样是最小深度
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。注意是叶子节点。
什么是叶子节点,左右孩子都为空的节点才是叶子节点!
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&&root.right!=null) return rightdepth+1;
if(root.left!=null&&root.right==null) return leftdepth+1;
int depth=Math.min(leftdepth,rightdepth)+1;
return depth;
}
}
方法二:层序遍历
只有当左右孩子都为空的时候,才说明遍历的最低点了。如果其中一个孩子不为空则不是最低点
class Solution {
public int minDepth(TreeNode root) {
Queue<TreeNode> queue=new LinkedList<>();
int depth=0;
if(root!=null) queue.offer(root);
while(!queue.isEmpty()){
int size=queue.size();
depth++;
for(int i=0;i<size;i++){
TreeNode node=queue.poll();
if (node.left == null && node.right == null) return depth;
if(node.left!=null) queue.offer(node.left);
if(node.right!=null) queue.offer(node.right);
}
}
return depth;
}
}
3. 完全二叉树的节点个数
方法一:递归法(后序遍历)
后序遍历,先求它的左子树的节点数量,再求右子树的节点数量,最后取总和再加一 (加1是因为算上当前中间节点)就是目前节点为根节点的节点数量
class Solution {
public int countNodes(TreeNode root) {
if(root==null) return 0;
int leftNum=countNodes(root.left);
int rightNum=countNodes(root.right);
int Num=leftNum+rightNum+1;
return Num;
}
}
方法二:迭代法(层序遍历)
class Solution {
public int countNodes(TreeNode root) {
if(root==null) return 0;
List<Integer> reList=new ArrayList<>();
Queue<TreeNode> queue=new LinkedList<>();
if(root!=null) queue.offer(root);
int sum=0;
while(!queue.isEmpty()){
int size=queue.size();
sum+=size;
while(size-->0){
TreeNode node=queue.poll();
if(node.left!=null) queue.offer(node.left);
if(node.right!=null) queue.offer(node.right);
}
}
return sum;
}
}
方法三:利用二叉树性质
利用完全二叉树性质,如某结点树为满二叉树直接用 2^树深度 - 1 来计算结点个数
class Solution {
public int countNodes(TreeNode root) {
if(root==null) return 0;
TreeNode left=root.left;
TreeNode right=root.right;
int leftdepth=0,rightdepth=0;
while(left!=null){
left=left.left;
leftdepth++;
}
while(right!=null){
right=right.right;
rightdepth++;
}
if(leftdepth==rightdepth) return (2<<leftdepth)-1;
return countNodes(root.left)+countNodes(root.right)+1;
}
}
1466

被折叠的 条评论
为什么被折叠?



