力扣 面试题34. 二叉树中和为某一值的路径 栈+dfs

https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/
力扣 面试题34. 二叉树中和为某一值的路径 栈+dfs_第1张图片

思路:搞个栈记录路径就行了,注意路径的定义……

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> stk;
    vector<vector<int>> ans;
    void dfs(TreeNode *root,int total,int sum)
    {
        if(root==NULL)
            return;
        stk.push_back(root->val);
        int val=total+root->val;
        if(root->left!=NULL)
            dfs(root->left,val,sum);
        if(root->right!=NULL)
            dfs(root->right,val,sum);
        if(root->left==NULL&&root->right==NULL&&val==sum)
            ans.push_back(stk);
        stk.pop_back();
    }

    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        dfs(root,0,sum);
        return ans;
    }
};

你可能感兴趣的:(面试题,DFS,栈)