二叉树的前序遍历C++实现(递归、迭代)

1、先定义二叉树的结构;
2、先序遍历为根左右;
3、递归实现时和我们的想法是一样的;
4、迭代实现时,需要借助栈,由于栈的性质,所以就有进栈顺序为右左跟的顺序,在根节点进栈时,需要加一个标识,本算法是多加了一个空指针,用于标记根节点;
5、二叉树的中序后序实现于前序遍历类似,请自己实现。

#include
#include
#include
using namespace std;
typedef struct TreeNode {
	int val;
	TreeNode* left;
	TreeNode* right;
	TreeNode* parent;
	TreeNode(int x) :val(x), left(nullptr), right(nullptr), parent(nullptr) {}
	void Connect(TreeNode* left, TreeNode* right)
	{
		if (left != nullptr)
		{
			left->parent = this;
		}
		if (right != nullptr)
		{
			right->parent = left;
		}
		this->left = left;
		this->right = right;
	}
};
/*前序递归实现*/
void PreOrede(TreeNode* root)
{
	if (root == nullptr)
		return;
	cout << root->val << " ";
	PreOrede(root->left);
	PreOrede(root->right);
	return;
}
void InOrede(TreeNode* root)
{
	if (root == nullptr)
		return;
	InOrede(root->left);
	cout << root->val << " ";
	InOrede(root->right);
	return;
}
/*前序迭代实现*/
vector<TreeNode*> PreOrder_diedai(TreeNode* root, vector<TreeNode*> result)
{
	stack<TreeNode*> st;
	
	st.push(root);
	while (!st.empty())
	{
		TreeNode* node = st.top();
		st.pop();
		if (node != nullptr)
		{
			if (node->right != nullptr)
				st.push(node->right);
			if (node->left != nullptr)
				st.push(node->left);
			st.push(node);
			st.push(nullptr);
		}
		else
		{
			result.push_back(st.top());
			st.pop();
		}
	}

	return result;
}
void main()
{
	TreeNode* node1 = new TreeNode(1);
	TreeNode* node2 = new TreeNode(2);
	TreeNode* node3 = new TreeNode(3);
	TreeNode* node4 = new TreeNode(4);
	TreeNode* node5 = new TreeNode(5);
	TreeNode* node6 = new TreeNode(6);
	TreeNode* node7 = new TreeNode(7);
	node1->Connect(node2, node3);
	node2->Connect(node4, node5);
	node3->Connect(node6, node7);
	PreOrede(node1);
	cout << endl;
	InOrede(node1);
	cout << endl;
	vector<TreeNode*> v1;
	v1 = PreOrder_diedai(node1, v1);
	cout << v1[0]->val<<endl;
	for (vector<TreeNode*>::iterator it = v1.begin(); it != v1.end(); it++)
		cout << ( * it)->val;
	cout << endl;
	system("pause");
}

你可能感兴趣的:(c++,算法,开发语言)