题目:
二叉树板子题目,主要考察的是二叉树路径存储和递归。
这种题不建议使用非递归遍历法写(我说的就是自己),因为会需要更多的辅助空间,同时左右子树切换和回溯条件是很难进行判断的。如果用递归就会好很多。
C++代码附带测试:
#include<iostream>
#include<vector>
#include<algorithm>
#include<stack>
using namespace std;
/**
* 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) {}
* };
*/
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){}
};
TreeNode* createTree(vector<int> a,int i){
if(a[i]==-1){
return nullptr;
}
TreeNode* root = new TreeNode(a[i]);
int leftson = i*2+1;
int rightson = i*2+2;
if(leftson<a.size()){
root->left = createTree(a,leftson);
}else{
root->left = nullptr;
}
if(rightson<a.size()){
root->right = createTree(a,rightson);
}else{
root->right = nullptr;
}
return root;
}
void inorder(TreeNode* root){
if(root==nullptr){
return;
}
inorder(root->left);
cout<<root->val<<" ";
inorder(root->right);
}
class Solution {
public:
vector<int> sup;
vector<vector<int>> ans;
void preorder(TreeNode* root, int target){
if(root==nullptr){
return;
}
target -= root->val;
sup.push_back(root->val);
if(target==0&&root->left==nullptr&&root->right==nullptr){
ans.push_back(sup);
}
preorder(root->left,target);
preorder(root->right,target);
sup.pop_back();
}
vector<vector<int>> pathSum(TreeNode* root, int target) {
preorder(root,target);
return ans;
}
};
int main(){
vector<int>a ={5,4,8,11,-1,13,4,7,2,-1,-1,-1,-1,5,1};
TreeNode* root = createTree(a,0);
inorder(root);
Solution solution;
vector<vector<int>> ans;
ans = solution.pathSum(root,22);
cout<<endl;
for(int i=0;i<ans.size();i++){
for(int j=0;j<ans[i].size();j++){
cout<<ans[i][j]<<" ";
}
cout<<endl;
}
}