class Solution {
public:
//求以root为根的树的左叶子节点和
int sumOfLeftLeaves(TreeNode* root) {
if(!root) return 0;
int sumLeft=sumOfLeftLeaves(root->left);
int sumRight=sumOfLeftLeaves(root->right);
//以上已经计算出分别求出左子树和右子树的左叶子之和,只需要求根节点的左叶子即可,只有当左孩子存在并且左孩子为叶子节点才有左叶子
int sumroot=0;
if(root->left&&!root->left->left&&!root->left->right){
sumroot=root->left->val;
}
return sumroot+sumLeft+sumRight;
}
};
class Solution {
public:
//递归先序,快排思想,与654最大二叉树类似
TreeNode* help(vector<int>&vec,int L,int R){
if(L>R) return nullptr;
int mid=L+(R-L)/2;
TreeNode* root=new TreeNode(vec[mid]);
root->left=help(vec,L,mid-1);
root->right=help(vec,mid+1,R);
return root;
}
TreeNode* sortedListToBST(ListNode* head) {
vector<int>vec;
while(head){
vec.push_back(head->val);
head=head->next;
}
return help(vec,0,vec.size()-1);
}
};
class Solution {
public:/*
从右往左累加所以遍历的顺序是右左中,并且也不需要返回值,
只需改变一下节点的值即可
*/
int sum=0;
void help(TreeNode* root){
if(!root) return;
help(root->right);
sum+=root->val;
root->val=sum;
help(root->left);
}
TreeNode* bstToGst(TreeNode* root) {
help(root);
return root;
}
};