104 二叉树的最大深度
题目链接:104 二叉树的最大深度
题目描述:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
解题思路:
- 使用迭代法。二叉树的最大深度,就是求有几层,因此,其跟层序遍历是一个道理。我们只需要在层序遍历的时候记下有几层即可。同理,最小深度也一样可以。
- 使用递归法。使用递归法的话,可以考虑前序,当然采用后序遍历也一样。这里采用前序遍历。
迭代法(层序遍历)
class Solution {
public:
int maxDepth(TreeNode* root) {
queue<TreeNode*>que;
if(root==NULL) return 0;
que.push(root);
int depth=0;
while(!que.empty())
{
int size=que.size();
for(int i=0;i<size;i++)
{
TreeNode* cur=que.front();
que.pop();
if(cur->left) que.push(cur->left);
if(cur->right) que.push(cur->right);
}
depth++;
}
return depth;
}
};
递归法(前序遍历)
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==NULL) return 0;
return 1+max(maxDepth(root->left),maxDepth(root->right));
}
};
111、二叉树的最小深度
题目链接:111二叉树的最小深度
题目描述
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
解题思路:跟二叉树的最大深度一样,也存在这迭代法和递归法两种方法。
迭代法(层序遍历)
class Solution {
public:
int minDepth(TreeNode* root) {
queue<TreeNode*>que;
if(root==NULL) return 0;
que.push(root);
int depth=1;
while(!que.empty())
{
int size=que.size();
for(int i=0;i<size;i++)
{
TreeNode* cur=que.front();
que.pop();
if(cur->left==NULL&&cur->right==NULL) return depth;
if(cur->left) que.push(cur->left);
if(cur->right) que.push(cur->right);
}
depth++;
}
return depth;
}
};
递归法(前序)
class Solution {
public:
int minDepth(TreeNode* root) {
if(root==NULL) return 0;
if(root->left==NULL&&root->right!=NULL) return 1+minDepth(root->right);
if(root->left!=NULL&&root->right==NULL) return 1+minDepth(root->left);
return 1+min(minDepth(root->left),minDepth(root->right));
}
};
222 完全二叉树的节点个数
题目链接:222 完全二叉树的节点个数
题目描述:
给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。
完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中
在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点
解题思路:遇上这题,大概都是直接统计节点的个数,不管是采用递归还是迭代,不管采用前序还是层序都可以直接统计节点个数。也不用注重是否是完全二叉树。可惜的是,超出了时间限制。因此,还是要仔细研究一下完全二叉树的相关特性。
超出时间限制的代码如下
class Solution {
public:
int countNodes(TreeNode* root) {
queue<TreeNode*> que;
if(root==NULL) return 0;
que.push(root);
int number=0;
while(!que.empty())
{
int size=que.size();
for(int i=0;i<size;i++)
{
TreeNode* cur=que.front();
que.pop();
number++;
if(root->left) que.push(root->left);
if(root->right) que.push(root->right);
}
}
return number;
}
};
根据完全二叉树写出的代码如下:
class Solution {
public:
int countNodes(TreeNode* root) {
int number=0;
if(root==NULL) return number;
int leftDepth=0,rightDepth=0;
TreeNode* left=root->left;
TreeNode* right=root->right;
while(left)
{
left=left->left;
leftDepth++;
}
while(right)
{
right=right->right;
rightDepth++;
}
if(leftDepth==rightDepth)
{
return (2 << leftDepth) - 1;
}
return countNodes(root->left) + countNodes(root->right) + 1;
}
};