[LeetCode] Path Sum II

vector<vector<int> > pathSum(TreeNode *root, int sum) {
	vector<vector<int>> path_sum;
	vector<TreeNode*> nodes;
	vector<vector<int>> paths;
	vector<int> sums;
	if(root != NULL)
	{
		nodes.push_back(root);
		sums.push_back(root->val);
		vector<int> path;
		path.push_back(root->val);
		paths.push_back(path);
	}
	while(!nodes.empty())
	{
		TreeNode* cur_node = nodes.back();
		//int cur_val = cur_node->val;
		int cur_sum = sums.back();
		vector<int> cur_path = paths.back();                        
		nodes.pop_back();
		paths.pop_back();
		sums.pop_back();     

		TreeNode* left_child = cur_node->left;
		TreeNode* right_child = cur_node->right;
		if(right_child != NULL)
		{
			nodes.push_back(right_child);               
			vector<int> right_path =  cur_path;
			right_path.push_back(right_child->val);
			paths.push_back(right_path);
			int right_sum = cur_sum + right_child->val;
			sums.push_back(right_sum);              
		}
		if(left_child != NULL)
		{
			nodes.push_back(left_child);
			vector<int> left_path = cur_path;
			left_path.push_back(left_child->val);
			paths.push_back(left_path);
			int left_sum = cur_sum + left_child->val;
			sums.push_back(left_sum);
		}
		if(left_child == NULL && right_child == NULL && cur_sum == sum)
		{
			path_sum.push_back(cur_path);                
		}            
	}
	return path_sum;
}
参考Binary Tree Postorder Traversal遍历方法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值