【劍指Offer系列34】二叉樹中和爲某一值的路徑

題目

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

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

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

返回:

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

提示:
節點總數 <= 10000

代碼

Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

# 思路:
# 這是二次樹的搜索問題,採用回溯法:BFS+路徑記錄
# 複雜度:
# O(N)
class Solution:
    def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
        res, path = [], [] # 結果列表,路徑列表
        
        def recur(root, sum):
            if not root: return
            path.append(root.val) # 路徑更新
            sum -= root.val # 目標值更新
            if sum == 0 and not root.left and not root.right:
                # 注意上述三條件缺一不可
                res.append(list(path)) # 正確路徑記錄,注意深拷貝
            recur(root.left, sum) # 左子樹
            recur(root.right, sum) # 右子樹
            path.pop() # 路徑恢復,這是回溯法的精髓
        
        recur(root, sum) # 根節點
        
        return res

C++

/**
 * 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>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> res;
        if (!root) return res;
        vector<int> path; 
        recur(root, res, path, sum);

        return res;
    }

    void recur(TreeNode* root, vector<vector<int>> &res, vector<int> path, int sum) {
        if (!root) return;
        sum -= root->val;
        path.push_back(root->val);
        if (sum == 0 && !root->left && !root->right) {
            res.push_back(path);
            return;
        }
        recur(root->left, res, path, sum);
        recur(root->right, res, path, sum);
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章