1. 程式人生 > 其它 >[題解]劍指 Offer 34. 二叉樹中和為某一值的路徑(C++)

[題解]劍指 Offer 34. 二叉樹中和為某一值的路徑(C++)

題目

輸入一棵二叉樹和一個整數,打印出二叉樹中節點值的和為輸入整數的所有路徑。從樹的根節點開始往下一直到葉節點所經過的節點形成一條路徑。

示例:
給定如下二叉樹,以及目標和target = 22,

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

返回:

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

提示:

  1. 節點總數 <= 10000

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof


著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

思路

DFS題,用一個數組path存當前遍歷到的路徑,當抵達葉節點且和為target的時候將path存入結果ans陣列中。遞迴時可以在經過一個節點時用target的值減去該節點的值,這樣最後只需要判斷target是否為0即可,用傳值的方法傳target。記得使用標記清除。
時間複雜度\(O(n^2)\),空間複雜度O(n)。

程式碼

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> ans;
    vector<int> path;

    vector<vector<int>> pathSum(TreeNode* root, int target) {
        if(!root) return ans;
        path.push_back(root->val);

        dfs(root, ans, path, target - root->val);
        return ans;
    }

    void dfs(TreeNode *cur, vector<vector<int>>& ans, vector<int>& path, int target)
    {
        if(target == 0 && !cur->left && !cur->right)
        {
            ans.push_back(path);
            return;
        }
        if(cur->left)
        {
            path.push_back(cur->left->val);
            dfs(cur->left, ans, path, target - cur->left->val);
            path.pop_back();
        }
        if(cur->right)
        {
            path.push_back(cur->right->val);
            dfs(cur->right, ans, path, target - cur->right->val);
            path.pop_back();
        }
    }
};