二叉树遍历递归、非递归

\二叉树代码、建树

void BTree::buildTree(vector<int>&a)//创建
{
	if (a.size() == 0)
	{
		return;
	}
	root = new TreeNode(a[0]);
	for (int i = 1; i < a.size(); i++)
	{
		TreeNode *newNode = new TreeNode(a[i]);
		TreeNode *node = root;
		while (node)
		{
			if (a[i] < node->val)
			{
				if (node->left == NULL)
				{
					node->left = newNode;
					break;
				}
				node = node->left;
			}
			else
			{
				if (node->right == NULL)
				{
					node->right = newNode;
					break;
				}
				node = node->right;
			}
		}
	}
}

\递归 先序、中序、后序遍历

void BTree::preOrder(TreeNode *root)//先序、根左右
{
	if (root == NULL)
	{
		return;
	}
	cout << root->val << " ";
	preOrder(root->left);
	preOrder(root->right);
}
void BTree::inOrder(TreeNode *root)//中序、左根右
{
	if (root == NULL)
	{
		return;
	}
	inOrder(root->left);
	cout << root->val << " ";
	inOrder(root->right);
}
void BTree::postOrder(TreeNode *root)//后序、左右根
{
	if (root == NULL)
	{
		return;
	}
	postOrder(root->left);
	postOrder(root->right);
	cout << root->val << " ";
}

\非递归 先序、中序、后序

void BTree::preOrderfor(TreeNode* root)//先序
{
	if (root == NULL)
	{
		return;
	}
	stack<TreeNode*>stk;
	stk.push(root);
	while (!stk.empty())
	{
		TreeNode *cur = stk.top();
		stk.pop();
		cout << cur->val << " ";
		if (cur->right)
		{
			stk.push(cur->right);
		}
		if (cur->left)
		{
			stk.push(cur->left);
		}
	}
}
void BTree::inOrderfor(TreeNode* root)//中序
{
	if (root == NULL)
	{
		return;
	}
	stack<TreeNode*>stk;
	TreeNode*  cur = root;
	while (!stk.empty() || cur != NULL)
	{
		while (cur != NULL)
		{
			stk.push(cur);
			cur = cur->left;
		}
		TreeNode *node = stk.top();
		stk.pop();
		cout << node->val << " ";
		cur = node->right;
	}	
}
void BTree::postOrderfor(TreeNode* root)//后序
{
	if (root == NULL)
	{
		return;
	}
	stack<TreeNode*>stk1;
	stack<TreeNode*>stk2;
	stk1.push(root);
	while (!stk1.empty())
	{
		TreeNode *cur = stk1.top();
		stk1.pop();
		stk2.push(cur);
		if (cur->left)
		{
            stk1.push(cur->left);
		}
		if (cur->right)
		{
		    stk1.push(cur->right);
		}
	}
	while (!stk2.empty())
	{
		cout << stk2.top()->val << " ";
		stk2.pop();
	}
}

层次遍历

void BTree::layerOrder(TreeNode* root)//层次遍历
{
	if (root == NULL)
	{
		return;
	}
	queue<TreeNode*>que;/
	que.push(root);
	TreeNode *last = root;
	TreeNode *nlast =NULL;
	while (!que.empty())
	{
		TreeNode *cur = que.front();
		que.pop();
		cout << cur->val << " ";
		if (cur->left)
		{
			que.push(cur->left);
			nlast = cur->left;
		}	
	
		if (cur->right)
		{
			que.push(cur->right);
			nlast = cur->right;
		}
		if (cur == last)
		{
			cout << endl;
			last = nlast;
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值