1. 程式人生 > >【LeetCode筆記】113. Path Sum II DFS搜尋+記錄節點

【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;
    }
};