[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遍历方法

你可能感兴趣的:(LeetCode,刷题)