LeetCode | Path Sum II

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


思路:此题与 Path Sum类似,只不过需要将路径上的点都输出来。如何做到?

添加一个辅助的向量v,用来记录到达第i层,第p个结点时,从根结点到p的父结点时路径上的所有结点。因此,当到达叶子结点时,这个辅助向量v就已经记录了到达该叶子结点前的所有结点。如果到达此叶子结点的路径符合要求,就将该叶子结点也放入辅助向量中,并将此辅助向量添加到最终的二维向量vv中。

class Solution {
public:
    vector<vector<int> > pathSum(TreeNode *root, int sum) 
	{
		   vector<int> v;
		   if(!root)
			   return vv;
		   else
		   {
			   path(root,0,sum,v);
		   }
		   return vv;
    }
	void path(TreeNode* root, int total, int sum, vector<int> v)
	{
		//toatl : 到目前结点root之前的路径上的所有元素和
		v.push_back(root->val);//push当前结点的值
		if(!root->left && !root->right)
		{
			if(total+root->val == sum)
				vv.push_back(v);
		}
		else if(root->left && !root->right)
		{
			path(root->left,total+root->val,sum,v);
		}
		else if(root->right && !root->left)
		{
			path(root->right,total+root->val,sum,v);
		}
		else
		{
			path(root->left,total+root->val,sum,v);
			path(root->right,total+root->val,sum,v);
		}
	}
private:
	vector<vector<int> > vv;
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值