二叉树的最大深度
题目:给定一个二叉树,找出其最大深度。二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
递归
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){// 终止条件
return 0;
}
int leftDepth = maxDepth(root.left);// 左
int rightDepth = maxDepth(root.right);// 右
int depth = 1 + Math.max(leftDepth,rightDepth);// 中,这里加1是因为当前节点算一层所有他的深度等于当前节点+左右子树的最大高度
return depth;
}
}
迭代
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
Deque<TreeNode> deque = new ArrayDeque<>();
deque.addLast(root);
int depth = 0;
while(!deque.isEmpty()){
int size = deque.size();
depth++;// 每一次外循环就是一层
while(size --> 0){
TreeNode node = deque.pollFirst();
if(node.left != null){
deque.addLast(node.left);
}
if(node.right != null){
deque.addLast(node.right);
}
}
}
return depth;
}
}
二叉树的最小深度
递归
思路:相较于二叉树的最大深度,本题的最小深度的定义是根节点到非空叶子节点,所以需要判断当前根节点的左右孩子是否为null
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){// 因为最小深度是根节点到叶子节点的距离,所以如果当前节点的左节点是null,则需要去找右节点的最小深度
return 1 + rightDepth;
}
if(root.left != null && root.right == null){// 同上
return 1 + leftDepth;
}
int depth = 1 + Math.min(leftDepth,rightDepth);
return depth;
}
}
迭代
class Solution {
public int minDepth(TreeNode root) {
if(root == null){
return 0;
}
Deque<TreeNode> deque = new ArrayDeque<>();
deque.addLast(root);
int depth = 0;
while(!deque.isEmpty()){
int size = deque.size();
depth++;
while(size --> 0){
TreeNode node = deque.pollFirst();
if(node.left == null && node.right == null){// 左右孩子都等于null的时候,就说明到了叶子节点
return depth;
}
if(node.left != null){
deque.addLast(node.left);
}
if(node.right != null){
deque.addLast(node.right);
}
}
}
return depth;
}
}
完全二叉树的节点个数
递归
思路:终止条件是:root==null;return 0
,采用后序遍历(因为统计个数需要左右孩子统计完了告诉根节点,也就是根节点需要收集左右孩子信息)
class Solution {
public int countNodes(TreeNode root) {
if(root == null){// 终止条件
return 0;
}
int leftCount = countNodes(root.left);// 左
int rightCount = countNodes(root.right);// 右
return leftCount + rightCount + 1;// 中
}
}
迭代
class Solution {
public int countNodes(TreeNode root) {
if(root == null){// 终止条件
return 0;
}
Deque<TreeNode> deque = new ArrayDeque<>();
deque.addLast(root);
int num = 0;
while(!deque.isEmpty()){
int size = deque.size();
num+=size;
while(size --> 0){
TreeNode node = deque.pollFirst();
if(node.left != null){
deque.addLast(node.left);
}
if(node.right != null){
deque.addLast(node.right);
}
}
}
return num;
}
}