LeetCode110.平衡二叉树
![](https://img-blog.csdnimg.cn/c0ce4fe0337c468daa96df410a893124.png)
class Solution {
public:
int getdepth(TreeNode* root){
if(root==NULL) return 0;
int lef = getdepth(root->left);
if(lef==-1)return -1;
int rig = getdepth(root->right);
if(rig==-1)return -1;
return abs(lef-rig)>1?-1:1+max(lef,rig);
}
bool isBalanced(TreeNode* root) {
if(root==NULL) return true;
int result = getdepth(root);
return result==-1?false:true;
}
};
257. 二叉树的所有路径
![](https://img-blog.csdnimg.cn/b3734a8d876e4669862ecddd4305b104.png)
/**
* 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 getpath(TreeNode* root,vector<int>& path,vector<string>& result){
path.push_back(root->val);
if(root->left==NULL&&root->right==NULL){
string s;
for(int i=0;i<path.size()-1;i++){
s+=to_string(path[i]);
s+="->";
}
s+=to_string(path[path.size()-1]);
result.push_back(s);
return;
}
if(root->left){
getpath(root->left,path,result);
path.pop_back();
}
if(root->right){
getpath(root->right,path,result);
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<int> path;
vector<string> result;
if(root==NULL)return result;
getpath(root,path,result);
return result;
}
};
404.左叶子之和
![](https://img-blog.csdnimg.cn/1c119b7bd7ba44c98ea631d8d37d6422.png)
/**
* 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 getleftnode(TreeNode* root,int& result){
if(root==NULL)return;
TreeNode* cur = root->left;
if(cur!=NULL&&cur->left==NULL&&cur->right==NULL){
result+=cur->val;
}
getleftnode(root->left,result);
getleftnode(root->right,result);
}
int sumOfLeftLeaves(TreeNode* root) {
int result=0;
getleftnode(root,result);
return result;
}
};