二叉树问题(1)--遍历

#include<iostream>
#include<stack>
using namespace std;
class Node
{
public:
	int val;
	Node* left;
	Node* right;
	Node(int val):val(val), left(NULL), right(NULL){}
	 
};

 
//先序遍历
void preOrder(Node* root)
{
	if (root == NULL)
	{
		return;
	}
	 
	 cout << root->val << " ";
	 preOrder(root->left);
	 preOrder(root->right);
	 
	

}

void NicepreOrder(Node* root)
{
	stack<Node*> s;
	if (root == NULL)
	{
		return;
	}
	s.push(root);
	while (!s.empty())
	{
		Node* root = s.top();
		s.pop();
		cout << root->val << " ";
		if (root->right != NULL)
		{
			s.push(root->right);
		}
		if (root->left != NULL)
		{
			s.push(root->left);
		}
		
	}
	cout << endl;
}

//中序遍历
void inOrder(Node* root)
{
	if (root == NULL)
	{
		return;
	}
	
	inOrder(root->left);
	cout << root->val << " ";
	inOrder(root->right);

}

void NiceinOrder(Node* root)
{
	stack<Node*> s;
	if (root == NULL)
	{
		return;
	}
	
	while (!s.empty() || root != NULL)//?
	{ 
		if (root != NULL)
		{
			s.push(root);
			root = root->left;
		}
		else
		{
			root = s.top();
			s.pop();
			cout << root->val << " ";
			root = root->right;
		}
		
	}
	cout << endl;
}

//后序遍历
void postOrder(Node* root)
{
	if (root == NULL)
	{
		return;
	}
	
	postOrder(root->left);
	postOrder(root->right);
	cout << root->val << " ";
}

void NicepostOrder(Node* root)
{
	stack<Node*> s;
	stack<Node*> s1;
	if (root == NULL)
	{
		return;
	}
	s.push(root);
	while (!s.empty())
	{
		Node* root = s.top();
		s.pop();
		s1.push(root);
		if (root->left != NULL)
		{
			s.push(root->left);
		}
		if (root->right != NULL)
		{
			s.push(root->right);
		}

	}
	while (!s1.empty())
	{
		Node* root = s1.top();
		s1.pop();
		cout << root->val << " ";
	}
	cout << endl;

}
int main()
{
	Node* head = new Node(5);
    head->left = new Node(3);
    head->right = new Node(8);
    head->left->left = new Node(2);
    head->left->right = new Node(4);
    head->left->left->left = new Node(1);
    head->right->left = new Node(7);
    head->right->left->left = new Node(6);
    head->right->right = new Node(10);
    head->right->right->left = new Node(9);
    head->right->right->right = new Node(11);

// recursive
	cout<<"==============recursive=============="<<endl;
    cout<<"pre-order: "<<endl;
	preOrder(head);
	cout << endl;
	cout<<"in-order: "<<endl;
	inOrder(head);
	cout<<endl;
	cout<<"pos-order: "<<endl;
	postOrder(head);
	cout<<endl;

// unrecursive
	cout<<"============unrecursive============="<<endl;
	NicepreOrder (head);
    NiceinOrder(head);
	NicepostOrder  (head);

	getchar();
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值