二叉树的前序中序遍历精华解(C++实现)

4 篇文章 0 订阅

结果明天更新变成了明年更新。
去年快手和字节面试时都考了二叉树的前序遍历非递归实现,等我以后要是面试人我也要考这个哈哈。

递归的英文是recursive,非加non。
非递归中序竟然是凭着之前的模糊记忆写的。
具体讲解有缘更新。

#include <iostream>
#include <vector>
#include <stack>
using namespace std;
struct TreeNode
{
	int val;
	TreeNode* left, *right;
	TreeNode(int _val):val(_val),left(nullptr),right(nullptr)
	{}
};

void digui_preOrder(TreeNode* root)
{
	if (!root)
		return;
	cout << root->val<<" ";
	digui_preOrder(root->left);
	digui_preOrder(root->right);
}

void digui_inOrder(TreeNode* root)
{
	if (!root)
		return;
	digui_inOrder(root->left);
	cout << root->val << " ";
	digui_inOrder(root->right);
}

void disdigui_preOrder(TreeNode* root)
{
	stack<TreeNode*> s;
	while (root||!s.empty())
	{
		if (!root)
		{
			root = s.top();
			s.pop();
		}
		cout << root->val;
		if (root->right)
			s.push(root->right);
		root = root->left;
	}
}

void disdigui_inOrder(TreeNode* root)
{
	stack<TreeNode*> s;
	while (root || !s.empty())
	{
		if (!root)
		{
			cout << s.top()->val << " ";
			root = s.top()->right;
			s.pop();
		}
		else
		{
			s.push(root);
	/*		if (root->right)
				s.push(root->right);*/
			root = root->left;
		}
	}
}
int main()
{
	TreeNode* root = new TreeNode(0);
	root->left = new TreeNode(1);
	root->right = new TreeNode(2);
	root->left->left = new TreeNode(3);
	root->left->right = new TreeNode(4);
	root->right->right = new TreeNode(5);
	digui_preOrder(root);
	cout << endl;
	disdigui_preOrder(root);
	cout << endl;
	digui_inOrder(root);
	cout << endl;
	disdigui_inOrder(root);
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值