104.二叉树的最大深度
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
给定一个二叉树 root
,返回其最大深度。
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
输入:root = [3,9,20,null,null,15,7] 输出:3
解题思路:
- 两种方法,层遍历迭代,递归法。
- 层遍历,每到一层就记录,全部遍历完后,返回最大层数。
- 递归法,每次调用函数则表示层数加1,当一个函数执行完则返回上一层,则减1。
广度迭代法:
public class Solution {
public int MaxDepth(TreeNode root) {
if(root == null) return 0;
Queue<TreeNode> q1 = new Queue<TreeNode>();
int deep = 0;
q1.Enqueue(root);
while(q1.Count > 0){
deep++;
int len = q1.Count;
while(len > 0){
TreeNode temp = q1.Dequeue();
if(temp.left != null) q1.Enqueue(temp.left);
if(temp.right != null) q1.Enqueue(temp.right);
len--;
}
}
return deep;
}
}
递归法:
public class Solution {
int res = 0;
public int MaxDepth(TreeNode root) {
GetDepth(root,res);
return res;
}
public void GetDepth(TreeNode root,int depth){
if(root== null) return;
depth++;
res = res > depth? res:depth;
GetDepth(root.left,depth);
GetDepth(root.right,depth);
depth--;
}
}
111.二叉树最小深度
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
输入:root = [3,9,20,null,null,15,7] 输出:2
解题思路:
- 上篇写了层迭代的解法,这次写递归解法。递归解法和104大同小异。
递归法:
public class Solution {
int res = int.MaxValue;
public int MinDepth(TreeNode root) {
if(root == null) return 0;
int deep = 0;
GetDepth(root,deep);
return res;
}
public void GetDepth(TreeNode root ,int depth){
if(root == null) return;
depth++;
if(root.left == null && root.right == null){
res = res < depth?res:depth;
}
GetDepth(root.left,depth);
GetDepth(root.right,depth);
depth--;
}
}
222.完全二叉树的节点个数
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
给你一棵 完全二叉树 的根节点 root
,求出该树的节点个数。
完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h
层,则该层包含 1~ 2h
个节点。
输入:root = [1,2,3,4,5,6] 输出:6
解题思路:
- 遍历方法还是递归的核心思想,每进入一个新的节点就让计数器自增1。
递归法:
public class Solution {
int res = 0;
public int CountNodes(TreeNode root) {
GetSum(root);
return res;
}
public void GetSum(TreeNode root){
if(root == null) return;
res++;
GetSum(root.left);
GetSum(root.right);
}
}
总结:
- 递归法万变不离其宗,要考虑好三点。1.参数和返回值。2.终止条件。3.递归逻辑。