LeetCode OJ 113. Path Sum II

topic

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \    / \
7    2  5   1

Return:

[
   [5,4,11,2],
   [5,8,4,5]
]

answer

It is DFS. It is enough to use a stack record to search the path. It should be noted that the node value is not necessarily a positive number, so it cannot be pruned. . .

Here is the code for AC:

/**
 * 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<vector<int>> ans;
    vector<int> stack;
    void search(TreeNode *node, int total, int sum){
        if(node == 0){
            return ;
        }
        total += node->val;
        stack.push_back(node->val);
        if(node->left == 0 && node->right == 0){
            if(total == sum){
                ans.push_back(vector<int>(stack.begin(), stack.end()));
            }
        }
        else{
            if(node->left != 0){
                search(node->left, total, sum);
            }
            if(node->right != 0){
                search(node->right, total, sum);
            }
        }
        stack.pop_back();
    }
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        search(root, 0, sum);
        return ans;
    }
};

124

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324841963&siteId=291194637