栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

算法竞赛入门经典 例题6-8

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

算法竞赛入门经典 例题6-8

UVa548

Tree

给定二叉树的中序遍历和后序遍历结果,输出从根节点到叶节点的路径和最小的叶节点的值,如果有多个叶节点满足上述条件,则输出值较小的叶节点。

依次遍历后序遍历的结果,在中序遍历中查找该元素,该元素右侧的就是该节点的右子树,左侧的就是该节点的左子树。

#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

struct Node
{
	int value;
	shared_ptr left, right;
};

class Solution
{
public:
	Solution(const vector &inorder, const vector &postorder)
	{
		vector::const_reverse_iterator PostIter = postorder.crbegin();
		ConstructBinaryTree(tree, inorder.begin(), inorder.end(), PostIter, postorder.rend());
	}
	int GetLeafValue()
	{
		TraverseLeafNode(tree, 0);
		return LeafValue;
	}
private:
	Node tree;
	int LeastSum = INT_MAX, LeafValue;
	void ConstructBinaryTree(Node &root,
		vector::const_iterator begin,
		vector::const_iterator end,
		vector::const_reverse_iterator &PostIter,
		vector::const_reverse_iterator PostEnd)
	{
		root.value = *PostIter++;
		vector::const_iterator RootIter = find(begin, end, root.value);
		if (RootIter + 1 != end) {
			root.right = make_shared();
			ConstructBinaryTree(*root.right, RootIter + 1, end, PostIter, PostEnd);
		}
		if (begin != RootIter) {
			root.left = make_shared();
			ConstructBinaryTree(*root.left, begin, RootIter, PostIter, PostEnd);
		}
	}
	void TraverseLeafNode(const Node &root, int sum)
	{
		if (root.left == nullptr && root.right == nullptr) {
			if (sum + root.value < LeastSum) {
				LeastSum = sum + root.value;
				LeafValue = root.value;
			}
			else if (sum + root.value == LeastSum) {
				LeafValue = min(LeafValue, root.value);
			}
			return;
		}
		if (root.left != nullptr) {
			TraverseLeafNode(*root.left, sum + root.value);
		}
		if (root.right != nullptr) {
			TraverseLeafNode(*root.right, sum + root.value);
		}
	}
};

vector ConverseInput(const string &input)
{
	vector ret;
	stringstream ss(input);
	int value;
	while (ss >> value) {
		ret.push_back(value);
	}
	return ret;
}

int main()
{
	string input;
	while (getline(cin, input)) {
		vector inorder = ConverseInput(input), postorder;
		getline(cin, input);
		postorder = ConverseInput(input);
		Solution solution(inorder, postorder);
		cout << solution.GetLeafValue() << endl;
	}
	return 0;
}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/297220.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号