提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
今天是跟着代码随想录刷题的第18天,主要是学了完全二叉树的节点数量和平衡二叉树。
一、完全二叉树的节点数量
思路:层序遍历直接做
class Solution {
public:
int countNodes(TreeNode* root) {
queue<TreeNode*> que;
int i=0;
if(root!=NULL) que.push(root);
while(!que.empty())
{
int size=que.size();
while(size--)
{
TreeNode*a=que.front();
que.pop();
i=i+1;
if(a->left) que.push(a->left);
if(a->right) que.push(a->right);
}
}
return i;
}
};
二、平衡二叉树
思路:就看左子树和右子树差的绝对值有没有大于1,再用递归。
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(getheight(root)!=-1) return true;
else return false;
}
int getheight(TreeNode* node)
{
if(node==NULL) return 0;
int left=getheight(node->left);
int right=getheight(node->right);
if(abs(left-right)>1||left==-1||right==-1) return -1;
else return 1+max(getheight(node->left),getheight(node->right));
}
};