インタビュー質問34:合計が
二分木の特定の値であるパス二分木と定数を入力し、二分木のノード値が入力整数であるすべてのパスを出力します。
ツリーのルートノードから始まり、リーフノードに至るまで、通過するノードはパスを形成します。
リートコードリンク:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/submissions/
class Solution
{
public:
vector<vector<int>> pathSum(TreeNode* root, int target)
{
vector<vector<int>> ans;
if(root == NULL)
return ans;
vector<int> path;
int sum = 0;
FindPath(root, target, ans, path, sum);
return ans;
}
void FindPath(TreeNode* root, int target, vector<vector<int>>& ans, vector<int>& path, int sum)
{
if(root == NULL)
return;
path.push_back(root->val);
sum += root->val;
bool isLeaf = (root->left == NULL && root->right == NULL);
if(isLeaf && sum == target)
ans.push_back(path);
if(root->left)
FindPath(root->left, target, ans, path, sum);
if(root->right)
FindPath(root->right, target, ans, path, sum);
path.pop_back();
}
};
前のコードでは、標準テンプレートライブラリのベクトルを使用してスタックを実装し、パスを保存します。push_backを使用してパスの最後にノードを追加し、pop_backを使用してパスの最後にノードを削除するたびに、したがって、スタックの最初のエントリが保証されます。後の特性。ここでSTLのスタックが直接使用されない理由は、スタックの最上位要素のみを取得できるためです。パスを出力するときは、パス上のすべてのノードを取得する必要があるため、std ::コードが実装されている場合、スタックは最適ではありません。選択してください。