学习文章链接:代码随想录
一、110.平衡二叉树
题目链接:110.平衡二叉树
思路:后序遍历 递归法
方法1:
class Solution {
public:
int getheight(TreeNode* node){
if(node==nullptr)return 0;
int left_h=getheight(node->left);
if(left_h==-1)return -1;
int right_h=getheight(node->right);
if(right_h==-1)return -1;
return abs(left_h-right_h)>1?-1:1+max(left_h,right_h);
}
bool isBalanced(TreeNode* root) {
return getheight(root)==-1?false:true;
}
};
二、257. 二叉树的所有路径
题目链接:257. 二叉树的所有路径
思路:递归和回溯
需要注意的点:终止条件的确定
方法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:
void travelpath(TreeNode* node,vector<int>& path,vector<string>& result){
path.push_back(node->val);
if(!node->left&&!node->right){
string spath;
for(int i=0;i<path.size()-1;i++){
spath += to_string(path[i]);
spath += "->";
}
spath += to_string(path[path.size()-1]);
result.push_back(spath);
}
if(node->left){
travelpath(node->left,path,result);
path.pop_back();
}
if(node->right){
travelpath(node->right,path,result);
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<int> path;
vector<string> result;
travelpath(root,path,result);
return result;
}
};
三、404.左叶子之和
题目链接:404.左叶子之和
思路:递归法,要多练习递归法。
方法1:
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(root=nullptr)return 0;
if(!root->left&&!root->right)return 0;
int leftvalue=sumOfLeftLeaves(root->left);
if(root->left&&!root->left->left&&!root->left->right){
leftvalue+=root->left->val;
}
leftvalue+=sumOfLeftLeaves(root->right);
return leftvalue;
}
};
四、222.完全二叉树的节点个数
题目链接:222.完全二叉树的节点个数
方法1:(层序遍历)
class Solution {
public:
int countNodes(TreeNode* root) {
queue<TreeNode*> que;
int results;
if(root==nullptr)return 0;
que.push(root);
while(!que.empty()){
int size=que.size();
for(int i=0;i<size;i++){
TreeNode* node=que.front();
results+=1;
que.pop();
if(node->left)que.push(node->left);
if(node->right)que.push(node->right);
}
}
return results;
}
};
方法2:(递归遍历)
class Solution {
public:
int sum(TreeNode* node){
if(node==nullptr)return 0;
int left=sum(node->left);
int right=sum(node->right);
return left+right+1;
}
int countNodes(TreeNode* root) {
return sum(root);
}
};
方法3:(利用完全二叉树的定义)
待二刷来补充