필기시험 문제--층차 입력 두 갈래 나무

2407 단어
어떤 두 갈래 나무에서 어떤 값의 모든 경로를 찾아내다
형식 입력:
첫 번째 줄 기대치
두 번째 줄은 층차순으로 훑어보는 순서에 따라 완전한 두 갈래 나무를 보여 줍니다.
 
입력:

6 3 1 # # 4 1 # # # # # # # 1
출력:
6 3 
6 1 1 1 
#define _CRT_SECURE_NO_WARINGS

#include 
#include 
#include 
#include 
#include 

using namespace std;

struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
		val(x), left(NULL), right(NULL) {
	}
};

void Find(TreeNode* root, int expectNumber, vector> &res, vector &path)
{
	path.push_back(root->val);
	expectNumber -= root->val;
	if (!root->left && !root->right)
	{
		if (expectNumber == 0)
			res.push_back(path);
	}
	if (root->left)
		Find(root->left, expectNumber, res, path);
	if (root->right)
		Find(root->right, expectNumber, res, path);
	path.pop_back();
}

vector> FindPath(TreeNode* root, int expectNumber) {
	vector> res;
	vector path;
	if (root)
		Find(root, expectNumber, res, path);
	return res;
}



TreeNode *ConstructBinaryTree(vector &arr, int len, int i) {
	if (len < 1)return NULL;
	TreeNode *root = NULL;
	if (i < len && arr[i] != "#") {
		int val;
		stringstream ss;
		ss << arr[i];
		ss >> val;
		root = new TreeNode(val);
		if (root == NULL) return NULL;
		root->left = ConstructBinaryTree(arr, len, 2 * i + 1);
		root->right = ConstructBinaryTree(arr, len, 2 * i + 2);
	}
	return root;
}

void PreOrderTra(TreeNode *root)     //  
{
	if (root != NULL)
	{
		cout << root->val << " ";
		PreOrderTra(root->left);
		PreOrderTra(root->right);
	}
	
}

int main()
{
	int expectNum;
	cin >> expectNum;

	vector vec;
	string input;
	while (cin >> input)
	{
		vec.push_back(input);
		if (getchar() == '
') break; } TreeNode* root = ConstructBinaryTree(vec, (int)vec.size(), 0); //PreOrderTra(root); vector> res = FindPath(root, expectNum); for (int i = 0; i < (int)res.size(); i++) { for (int j = 0; j < (int)res[i].size(); j++) cout << res[i][j] << " "; cout << endl; } system("pause"); }

좋은 웹페이지 즐겨찾기