222.完全二叉树的节点个数
题目
直接用递归的方式求完全二叉树是可以的,但这样就等于把它当成了普通二叉树,没有利用到二叉树的特性,也就是只有最下面一层是不满的,而且从左到右连续。
如果能确定左子树是否为满二叉树,则可以利用pow(2,depth)-1直接求出数量。
可以利用一直向左遍历的深度和一直向右遍历的深度来判断是否是满二叉树,因为根据完全二叉树的性质,如果深度一样那中间必有节点。
int countNode(TreeNode* root){
if(root==NULL) return 0;
TreeNode* curl=root;
TreeNode* curr=root;
int left=1,right=1;
while(curl->left!=NULL){
curl=curl->left;
left++;
}
while(curr->right!=NULL){
curr=curr->right;
right++;
}
if(left==right){//满二叉树
return pow(2,left)-1;
int l=countNode(root->left);
int r=countNode(root->right);
return l+r+1;
}
110.平衡二叉树
题目
和求深度的大差不差,但是需要判断左右深度的差值是否超过1;
一开始借用了求深度的递归函数。
然后再bool函数上加了
{int result=abs(left-right);
if(result==0||result==1){
return panduan(root->left)&&panduan(root->right);
else
return false;
}
但是可以直接在求深度时判断左右差值,如果大于1的话就把depth设为一个特殊值-1,最后判断depth是否是-1;
int getdepth(TreeNode* root){
if(root==NULL) return 0;
int leftd=getdepth(root->left);
if(left==-1) return-1;
int rightd=getdepth(root->right);
if(rightd==-1) return -1;
if(abs(leftd-rightd)>1)
return -1;
return max(leftd,rightd)+1;
257. 二叉树的所有路径
这里初步用到了回溯的思想,首先可以用一个数组来记录走过的路径。
要先记录中间节点,所以是前序遍历。
1.确定函数和参数
一般和回溯有关的用void
void getpath(TreeNode* root,vector<int> &path,vector<string> result){
if(root==NULL) return;
path.push_back(root->val);
if(root->left==NULL&&root->right==NULL){//则说明走完了一整条路径,开始记录
string temp;
for(int num:path){
temp+=to_string(num);
temp+="->";
}
temp.pop_back();
temp.pop_back();//删掉最后一组->
result.push_back(string);
}
if(root->left!=NULL){
getpath(root->left,path,result);//在通过一条交叉路口要回退
path.pop_back();
}
if(root->right!=NULL){
getpath(root->right,path,result);
path.pop_back();
}
}
注意要使用引用传递而不是拷贝传递,不然每次填入的都不在一个result里,road也是,应该共同修改或维护一个road.
不然每一层的path只能弹出它获得过的,比如第一层的只能弹出根节点。
404.左叶子之和
题目
判断是不是左叶子只能通过它的父叶子来判断,
if(root->left!=NULL&&root->left->leftNULL&&root->left->rightNULL)
l=root->left->val;
int sumOfLeftLeaves(TreeNode* root) {
if(root==NULL) return 0;
int l=sumOfLeftLeaves(root->left);
if(root->left!=NULL&&root->left->left==NULL&&root->left->right==NULL){
l=root->left->val;
}
int r=sumOfLeftLeaves(root->right);
return l+r;
}