【LeetCode笔记】113. Path Sum II DFS搜索+记录节点

题目:

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

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

Subscribe to see which companies asked this question.

思路:典型的 深度优先搜索~遍历每一条到叶子节点的路径并且记录下来,如果一路上的总和等于sum就把路径保存下来。

使用递归的办法,如果当前节点是叶子结点,且值等于sum,则把该节点放入一个vector v1,并且把整个v1放入结果v中(注意!这只说明当前这条路走完了,还要把最后一个节点拿出来,回到叶子节点之前的状态。举例:目前在11这个节点,走到7时,先把7放入v1,发现总和不相等,那么要把7拿出来,才能继续递归);如果当前节点不是叶子节点或者值不等于sum,这把这个节点的值放入v1中暂存,继续加入v1的左右节点进行递归。同样的,左右节点递归完后需要把此节点拿出来。

/**
 * 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:
    void re(TreeNode* root, int sum,vector<vector<int>>&v, vector<int> &v1){
        if(root==NULL)
            return;
        if((root!=NULL)&&(root->left==NULL)&&(root->right==NULL)&&(sum == root->val)){
            v1.push_back(root->val);
            v.push_back(v1);
            v1.pop_back();
            //printf("root = %d\nsum = %d\n",root->val,sum);
        }
        else{
            v1.push_back(root->val);
            re(root->left,sum-root->val,v,v1);
            re(root->right,sum-root->val,v,v1);
            v1.pop_back();
        }
    }
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> v;
        vector<int> v1;
        re(root,sum,v,v1);
        return v;
    }
};


猜你喜欢

转载自blog.csdn.net/macidoo/article/details/70185205