題目描述:
輸入一顆二叉樹和一個整數(shù)非剃,打印出二叉樹中結(jié)點值的和為輸入整數(shù)的所有路徑聂喇。路徑定義為從樹的根結(jié)點開始往下一直到葉結(jié)點所經(jīng)過的結(jié)點形成一條路徑舟奠。
關(guān)鍵點:1. 二叉樹暴匠、遞歸
2.因為路徑是從根節(jié)點開始鞍恢,因此,最先遍歷的應(yīng)該是根節(jié)點,所以應(yīng)該考慮前序遍歷
3.如果遍歷到葉子節(jié)點發(fā)現(xiàn)不符條件帮掉,此時應(yīng)該采用回溯弦悉,吐出葉子節(jié)點。
class Solution {
public:
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
vector<vector<int>> ret;
vector<int> temp;
int currentSum = 0;
if(root == NULL)
return ret;
findPath(root, currentSum, ret, expectNumber, temp);
return ret;
}
void findPath(TreeNode* root, int currentSum, vector<vector<int> >&ret, int expectNumber, vector<int>&temp){
currentSum += root -> val;
temp.push_back(root -> val);
bool isLeaf = root -> left == NULL && root -> right == NULL;
if(currentSum == expectNumber && isLeaf){//是葉子節(jié)點且路徑節(jié)點和與給定值相同
ret.push_back(temp);
}
//如果不是葉子節(jié)點蟆炊,則遍歷它的子節(jié)點
if(root -> left != NULL)
findPath(root -> left, currentSum, ret, expectNumber, temp);
if(root -> right != NULL)
findPath(root -> right, currentSum, ret, expectNumber, temp);
//返回父節(jié)點之前稽莉,在路徑上刪除當前節(jié)點
temp.pop_back();
}
};