輸入一顆二叉樹和一個整數,打印出二叉樹中結點值的和為輸入整數的所有路徑。路徑定義為從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。


// ConsoleApplication2.cpp : 定義控制台應用程序的入口點。 //

#include "stdafx.h"
#include "stdafx.h"
#include<iostream>
#include<vector>
#include<algorithm>
#include<numeric>
#include<list>
#include<iterator>
#include<queue>
#include<stack>
#include<algorithm>
using namespace std;





struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
	val(x), left(NULL), right(NULL) {
	}
};
class Solution {
public:
	int sum = 0;
	vector<int> path;
	vector <vector<int>> paths;
	int flag = 0;

	vector<vector<int> > FindPath(TreeNode* root, int expectNumber) {

		paths = {};
		
		if (root != NULL)
		{ 
			FindOnePath(root, expectNumber);
		
		}
		
		
		///*if (root != NULL) FindOnePath(root, expectNumber);
		//	
		//else  paths = {};*/
		//
		return paths;
	}

	void FindOnePath(TreeNode* &root, int expectNumber) {
	
		if (root == NULL)
		{
			if(flag==0)

			{ 
			
			sum = 0;
			for (auto it = path.begin(); it != path.end(); ++it)
				sum += *it;
			if (sum == expectNumber)
			{
				paths.push_back(path);
			}
			flag = 1;
			}
			else
			{
				flag = 0;
			}
			return;

		}
		else
		{
			path.push_back(root->val);
			cout << "push:"<<root->val<<endl;
			FindOnePath(root->left, expectNumber); //第二次犯這個錯誤了,記住這里調用的是FindOnePath,而不是FindPath
			
			FindOnePath(root->right, expectNumber);
			path.pop_back();
			cout << "pop :" << root->val << endl;
		}
	
	}

	
	void CreateBiTree(TreeNode* &T) //這里的引用 & 必須,要不然會報未初始化變量
	{
		int num = 0;
		cin >> num;
		if (num == 0) return;
		else
		{
			T = new TreeNode(num);
			CreateBiTree(T->left);
			CreateBiTree(T->right);
		}
	}
	
};

int main()
{
	
	Solution so;
	TreeNode *T;
	so.CreateBiTree(T);
	cout << "創建二叉樹成功!"<<endl;

	vector<vector<int>> vec;
	vec = so.FindPath(T,1);

	for (auto it = vec.begin(); it != vec.end(); it++)
	{
		for (auto i = (*it).begin(); i != (*it).end(); i++)
			cout << *i << "  ";
		cout << endl;
	}



	return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM