DS007-binary tree-binary linked list notation-first root-middle root-post root traversal

 This article introduces the binary list representation of a binary tree, and its first, middle and last root traversal.

Take the following binary tree as an example.



#include "stdafx.h"


#include<iostream> 
using namespace std;

template<typename T> class tree
{//基于二叉链表的二叉树
	struct node
	{
		T data;
		node *lchild;
		node *rchild;

	};
	node *root;
	node a, b, c, d, e;
public:
	tree()
	{//构造函数,一棵静态二叉树
		root = &a;
		a.data = 'a';
		b.data = 'b';
		c.data = 'c';
		d.data = 'd';
		e.data = 'e';
		a.lchild = &b;
		a.rchild = &c;
		c.lchild = &d;
		c.rchild = &e;
		d.lchild = d.rchild = 0;
		e.lchild = e.rchild = 0;

	}
	void preTraverse(node *root)
	{//先根遍历
		if (root)
		{
			cout << root->data << " ";
			preTraverse(root->lchild);
			preTraverse(root->rchild);
		}

	}
	void preTraverse()
	{//先根遍历
		preTraverse(root);
	}
	void InTraverse(node *root)
	{//中根遍历
		if (root)
		{
			InTraverse(root->lchild);
			cout << root->data << " ";
			InTraverse(root->rchild);
		}

	}
	void InTraverse()
	{
		InTraverse(root);

	}
	void postTraverse(node *root)
	{//后根遍历
		if (root)
		{
			postTraverse(root->lchild);
			postTraverse(root->rchild);
			cout << root->data << " ";
		}

	}
	void postTraverse()
	{
		postTraverse(root);
	}

};


int main()
{
	tree<char> t;
	t.preTraverse();
	cout << endl;
	t.InTraverse();
	cout << endl;
	t.postTraverse();
	cout << endl;
	

	return 0;
}


 

Guess you like

Origin blog.csdn.net/weixin_43917370/article/details/108609048