C++

智能指针&二叉树遍历

C++常见问题(五)

Posted by Francis-wu on February 15, 2019

回顾复习一些常见的C++问题,以及一些没有仔细考虑过的地方。(任何问题欢迎邮件:admin@franciswu.top

#include <iostream>
#include <memory>
#include <string>
using namespace std;

template<typename T>
T adder(T v) {
	return v;
}
template<typename T, typename... Args>
T adder(T first, Args... args) {
	return first + adder(args...);
}

struct node
{
	weak_ptr<node> left;
	weak_ptr<node> right;

	string data;

	node(const char* D) { data = string(D); }
};

//先根遍历
void preRoot(const shared_ptr<node> & root)
{
	cout << root->data;

	//左
	if (!root->left.expired())
	{
		preRoot(root->left.lock());
	}

	//右
	if (!root->right.expired())
	{
		preRoot(root->right.lock());
	}

}

//中根遍历
void midRoot(const shared_ptr<node> & root)
{
	//左
	if (!root->left.expired())
	{
		midRoot(root->left.lock());
	}

	cout << root->data;

	//右
	if (!root->right.expired())
	{
		midRoot(root->right.lock());
	}
}

//后根遍历
void lateRoot(const shared_ptr<node> & root)
{
	//左
	if (!root->left.expired())
	{
		lateRoot(root->left.lock());
	}

	//右
	if (!root->right.expired())
	{
		lateRoot(root->right.lock());
	}

	cout << root->data;
}


void main()
{
	shared_ptr<node> root(new node("A"));

	shared_ptr<node> B(new node("B"));
	shared_ptr<node> C(new node("C"));
	shared_ptr<node> D(new node("D"));
	shared_ptr<node> E(new node("E"));
	shared_ptr<node> F(new node("F"));
	shared_ptr<node> G(new node("G"));
	shared_ptr<node> H(new node("H"));
	shared_ptr<node> I(new node("I"));

	root->left = B;
	root->right = C;

	B->right = D;

	D->left = E;
	D->right = F;

	C->left = G;
	G->right = H;

	H->left = I;

	system("pause");
}