《剑指offer》面试题34. 二叉树中和为某一值的路径

问题描述

输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
示例:
给定如下二叉树,以及目标和 sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1
返回:

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

提示:

节点总数 <= 10000

代码

注意加上return,找到一个路径就会退出,适宜于检查是否存在这样的路径。

/**
 * 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>> ans;
        vector<int> path;
        int target = sum;
        sum = 0;
        function(root,sum,target,path,ans);
        return ans;
    }
    void function(TreeNode* root,int& sum,int &target,vector<int> &path,vector<vector<int>>& ans)
    {       
        if(!root)return;
        path.push_back(root->val);
        sum += root->val;
        if(sum == target && !root->left && !root->right)
        {
            ans.push_back(path);
            //return;
        }       
        if(root->left)function(root->left,sum,target,path,ans);
        if(root->right)function(root->right,sum,target,path,ans);
        path.pop_back();
        sum -= root->val;
    }
};

结果

执行用时 :12 ms, 在所有 C++ 提交中击败了82.88%的用户
内存消耗 :19.9 MB, 在所有 C++ 提交中击败了100.00%的用户
posted @ 2020-04-25 08:48  曲径通霄  阅读(98)  评论(0编辑  收藏  举报