笔试题--层序输入一颗二叉树

在某一棵二叉树中找出和为某一值的所有路径

输入格式:

第一行 期望值

第二行 按照层序遍历顺序给出的完全二叉树, 若空用 # 表示

 

输入:

9

6 3 1 # # 4 1 # # # # # # # 1

输出:

6 3 

6 1 1 1 

#define _CRT_SECURE_NO_WARINGS

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <sstream>

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<vector<int>> &res, vector<int> &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<vector<int>> FindPath(TreeNode* root, int expectNumber) {
	vector<vector<int>> res;
	vector<int> path;
	if (root)
		Find(root, expectNumber, res, path);
	return res;
}



TreeNode *ConstructBinaryTree(vector<string> &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<string> vec;
	string input;
	while (cin >> input)
	{
		vec.push_back(input);
		if (getchar() == '\n') break;
	}

	TreeNode* root = ConstructBinaryTree(vec, (int)vec.size(), 0);
	
	//PreOrderTra(root);
	vector<vector<int>> 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");
}


 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值