就层序遍历后reverse一下
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
queue<TreeNode*> que;
if(root!=nullptr)
que.push(root);
vector<vector<int>> result;
while(!que.empty()){
int size=que.size();
vector<int> vec;
for(int i=0;i<size;i++)
{
TreeNode* node=que.front();
que.pop();
vec.push_back(node->val);
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
result.push_back(vec);
}
reverse(result.begin(),result.end());
return result;
}
};
先用快慢指针找中点,再递归构造二叉搜索树
类似二分
class Solution {
public:
ListNode* midNode(ListNode* left,ListNode* right){
ListNode *fast,*slow;
fast=left;
slow=left;
while(fast!=right&&fast->next!=right)
{
fast=fast->next;
fast=fast->next;
slow=slow->next;
}
return slow;
}
TreeNode* buildTree(ListNode* left,ListNode* right){
if(left==right)
return nullptr;
ListNode* mid=midNode(left,right);
TreeNode* root=new TreeNode(mid->val);
root->left=buildTree(left,mid);
root->right=buildTree(mid->next,right);
return root;
}
TreeNode* sortedListToBST(ListNode* head) {
return buildTree(head,nullptr);//左闭右开区间
}
};
112是返回有没有总和为给定值的路径,这道题是返回所有总和为给定值的路径
因此要遍历整个树,找到所有路径,且不用处理递归返回值,所以递归函数不要返回值!
void traversal(TreeNode* cur, int count)
if(count==0&&!cur->left&&!cur->right){
result.push_back(path);
return;
}
else if (!cur->left && !cur->right)
return;
if(cur->left)
{
path.push_back(cur->left->val);
count-=cur->left->val;
traversal(cur->left,count);
count+=cur->left->val;
path.pop_back();
}
if(cur->right)
{
path.push_back(cur->right->val);
count-=cur->right->val;
traversal(cur->right,count);
count+=cur->right->val;
path.pop_back();
}
整体代码
class Solution {
public:
vector<int> path;
vector<vector<int>> result;
void traversal(TreeNode* cur, int count)
{
if(count==0&&!cur->left&&!cur->right){
result.push_back(path);
return;
}
else if (!cur->left && !cur->right)
return;
if(cur->left)
{
path.push_back(cur->left->val);
count-=cur->left->val;
traversal(cur->left,count);
count+=cur->left->val;
path.pop_back();
}
if(cur->right)
{
path.push_back(cur->right->val);
count-=cur->right->val;
traversal(cur->right,count);
count+=cur->right->val;
path.pop_back();
}
return;
}
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
result.clear();
path.clear();
if (root == NULL) return result;
path.push_back(root->val); // 把根节点放进路径
traversal(root, targetSum - root->val);
return result;
}
};
这不就是前序遍历
其实要做的就是按前序序列创建一个树,每个节点只有右子树