【剑指Offer】面试题34. 二叉树中和为某一值的路径

题目

输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。

示例:
给定如下二叉树,以及目标和 sum = 22,

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

返回:

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

提示:
节点总数 <= 10000

本题同【LeetCode】113. 路径总和 II

思路一:回溯

代码

class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> res;
        if (root) {
            vector<int> path;
            find(root, sum, res, path);
        }
        return res;
    }

    void find(TreeNode *root, int sum, vector<vector<int>> &res, vector<int> &path) {
        sum -= root->val;
        path.push_back(root->val);
        if (sum == 0 && !root->left && !root->right) {
            res.push_back(path);
            return;
        }
        if (root->left) {
            find(root->left, sum, res, path);
            path.pop_back(); //回溯
        }
        if (root->right) {
            find(root->right, sum, res, path);
            path.pop_back(); //回溯
        }
    }
};

另一种写法

class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> res;
        vector<int> path;
        if (!root) {
            return res;
        }
        find(root, sum, res, path);
        return res;
    }
    void find(TreeNode *root, int sum, vector<vector<int>> &res, vector<int> &path) {
        if (!root) {
            return;
        }
        path.push_back(root->val);
        if (!root->left && !root->right && sum == root->val) {
            res.push_back(path);
        }
        find(root->left, sum-root->val, res, path);
        find(root->right, sum-root->val, res, path);
        path.pop_back();
    }
};

猜你喜欢

转载自www.cnblogs.com/galaxy-hao/p/12374938.html