104.二叉树的最大深度
题目:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
概念
深度:任意一个节点到根节点的距离(从1开始数)
高度:根节点到任意节点的距离(从1开始)
遍历方式
高度:后序
深度:前序
思路
递归
1.左孩子高度
2.右孩子高度
3.中间高度等于左右孩子高度+1
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
return getHeight(root);
}
public int getHeight(TreeNode root){
if(root==null)return 0;
int leftHeight=getHeight(root.left);
int rightHeight=getHeight(root.right);
return Math.max(leftHeight,rightHeight)+1;
}
}
111.二叉树的最小深度
题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
思路
首先求出左根节点的最小高度再求右根节点最小高度,再取最小值。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if(root==null)return 0;
int leftDep=minDepth(root.left);
int rightDep=minDepth(root.right);
if(root.left==null)return rightDep+1;
if(root.right==null)return leftDep+1;
return Math.min(leftDep,rightDep)+1;
}
}
222.完全二叉树的节点个数
题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
代码
class Solution {
public int countNodes(TreeNode root) {
if(root==null)return 0;
return countNodes(root.left)+countNodes(root.right)+1;
}
}
思路
节点个数为左节点个数+右节点个数+1