113. Path Sum II

题目描述

Given a binary tree and a sum, find all root-to-leaf paths where each paths 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]
]

/**
 * Definition for binary tree
 * 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>> ret;
    	if(root == nullptr)
    		return ret;

    	vector<int> temp;
    	pathSumCore(root,sum,ret,temp);
    	return ret;       
    }
    //递归接口参数的设计,是为了我们更加方便的保存一些临时的信息
    void pathSumCore(TreeNode *root,int sum,vector<vector<int>> &ret,vector<int> &temp)
    {
    	int val = root->val;
    	temp.push_back(val);
    	int curSum = sum - val;
    	if(curSum == 0 && root->left==nullptr && root->right==nullptr)
    	{
    		ret.push_back(temp);
            //这里遵循的原则是把参数的状态恢复原则,进来时是
            //什么状态,函数退出时还是什么状态,保持一致性,
            //避免出现错误
    		temp.pop_back();
    		return;
    	}

    	if(root->left!=nullptr)
    		pathSumCore(root->left,curSum,ret,temp);
    	if(root->right!=nullptr)    		
    		pathSumCore(root->right,curSum,ret,temp);

    	temp.pop_back();
    	return;
    }
};

posted on 2021-06-12 08:16  朴素贝叶斯  阅读(22)  评论(0编辑  收藏  举报

导航