時間限制:C/C++ 1秒,其他語言2秒 空間限制:C/C++ 32M,其他語言64M 熱度指數:589567
本題知識點: 樹
題目描述
輸入一顆二叉樹的根節點和一個整數,打印出二叉樹中結點值的和爲輸入整數的所有路徑。路徑定義爲從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。一看就是後序遍歷。
解答:
遞歸方法:
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
private:
vector<vector<int> >re;
vector<int>temp;
public:
vector<vector<int> > FindPath(TreeNode* root,int n) {
//在 Dev C++ 中,上面寫法中 int 後面的兩個>之間需要有空格,
//否則有的編譯器會把它們當作>>運算符,編譯會出錯。
if(root==NULL){
return re;
}
int rootnum=root->val;
int sum=n-rootnum;
temp.push_back(rootnum);
FindPath(root->left,sum);
if(root->left!=NULL)temp.pop_back();
FindPath(root->right,sum);
if(root->right!=NULL)temp.pop_back();
if(root->left==NULL&&root->right==NULL){
if(rootnum==n){
re.push_back(temp);
}
}
return re;
}
};
非遞歸方法:
class Solution {
public:
vector<vector<int> > FindPath(TreeNode* root, int n) {
//在 Dev C++ 中,上面寫法中 int 後面的兩個>之間需要有空格,
//否則有的編譯器會把它們當作>>運算符,編譯會出錯。
vector<vector<int> >re;
vector<int>temp;
vector<TreeNode*>tempsc;
stack<TreeNode*>sc;
TreeNode*p = root;
TreeNode*pre = NULL;
int sum = 0;
int recount = 0;
while (p != NULL || !sc.empty()){
if (p != NULL){//注意這裏是if就可以,用來檢測有沒有左節點。
sum = sum + p->val;
sc.push(p);
p = p->left;
}
else{
p = sc.top();
p = p->right;
if (p != NULL&&p != pre){//用來檢測有沒有右節點。
sc.push(p);
sum = sum + p->val;
p = p->left;
}
else{
int topnum = sc.top()->val;
p = sc.top();
//給指針賦值別總忘記。
if (sum == n&&p->right==NULL){
recount++;
while (!sc.empty()){
tempsc.push_back(sc.top());
temp.push_back(sc.top()->val);
sc.pop();
}
reverse(tempsc.begin(), tempsc.end());
reverse(temp.begin(), temp.end());
for (int i = 0; i<tempsc.size(); i++){
sc.push(tempsc[i]);
}
re.push_back(temp);
temp.clear();
tempsc.clear();
}
sc.pop();
sum = sum - topnum;
pre = p;
p = NULL;
//訪問完別忘記置空,只有置空纔可以知道該節點的左節點訪問結束了,形成完整的邏輯鏈
}
}
}
return re;
}
};