LeetCode OJ 113. Path Sum II

题目

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]
]

解答

就是DFS,用一个堆栈记录搜索路径就可以了,需要注意的是节点值不一定是正数,所以无法剪枝什么的。。。

下面是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

猜你喜欢

转载自www.cnblogs.com/YuNanlong/p/8908664.html