104. 二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
方法一-递归
思考:
- 高度和深度一般不同,深度是指从上往下,高度是指从下往上。但这边求的是最大深度,所以根节点的高度就是二叉树的最大深度。
- 若采用后序遍历(左右中),在递归中 空节点就是递归的终止条件,为0. 单层递归中,取左右深度的最大值+1就是目前为根节点的树的深度(+1是为了算上此时的中间节点)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int getDepth(TreeNode* root) //返回的是高度所以用int
{
if(root == nullptr) return 0;
int leftdepth = getDepth(root->left);
int rightdepth = getDepth(root->right);
int depth = 1+max(leftdepth,rightdepth);
return depth;
}
int maxDepth(TreeNode* root) {
return getDepth(root);
}
};
111. 二叉树的最小深度
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
输入: root = [3,9,20,null,null,15,7]
输出: 2
输入: root = [2,null,3,null,4,null,5,null,6]
输出: 5
思考:
- 要注意什么是叶子节点,左右孩子都为空的节点才是叶子节点!
- 求二叉树的最小深度和求二叉树的最大深度的差别主要在于处理左右孩子不为空的逻辑。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int getDepth(TreeNode* root)
{
if(root==nullptr) return 0;
int leftDepth = getDepth(root->left);
int rightDepth = getDepth(root->right);
//左为空 右不为空,此时并不是最低点
if(root->left == nullptr && root->right != nullptr)
{
return 1+rightDepth;
}
//左不为空, 右为空 此时也不是最低点
if(root->left != nullptr && root->right == nullptr)
{
return 1+leftDepth;
}
int result = 1+min(leftDepth,rightDepth);
return result;
}
int minDepth(TreeNode* root) {
return getDepth(root);
}
};
222. 完全二叉树的节点个
给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。
完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。
输入: root = [1,2,3,4,5,6]
输出: 6
输入: root = []
输出: 0
方法一-递归
思考: 确定单层递归的逻辑:先求它的左子树的节点数量,再求右子树的节点数量,最后取总和再加一 (加1是因为算上当前中间节点)就是目前节点为根节点的节点数量。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
int getNodesum(TreeNode* cur)
{
if(cur==nullptr) return 0;
//后序遍历 左右中
int leftNum = getNodesum(cur->left);
int rightNum = getNodesum(cur->right);
int treeNum = leftNum+rightNum+1;
return treeNum;
}
public:
int countNodes(TreeNode* root) {
return getNodesum(root);
}
};