二叉树的前序遍历后序遍历中序遍历的非递归实现以及相应的拓展

二叉树的前序遍历后序遍历中序遍历的非递归实现以及相应的拓展

//树的后序遍历
void houxu(TreeNode* root)
{
	int top = -1;
	int flag[10000];
	
	stack<TreeNode*> s_t;
	TreeNode* p = root;	
	while (!s_t.empty() || p != NULL)
	{
		while (p != NULL)
		{
			++top;
			s_t.push(p);
			flag[top] = 0;
			p = p->left;
		}
		//这里不需要的
		while (top >= 0 && flag[top] == 1)//只有当右节点被访问到了才能访问根
		{
			--top;
			cout << s_t.top()->val << endl;
			s_t.pop();
		}
		if (!s_t.empty())
		{
			TreeNode* temp = s_t.top();
			p = temp->right;
			flag[top] = 1;
		}
	}
}
//树的中序遍历
void zhongxu(TreeNode* root)
{
	TreeNode* p = root;
	stack<TreeNode*> s_t;
	while (!s_t.empty() || p != NULL)
	{
		while (p != NULL)
		{
			s_t.push(p);
			p = p->left;
		}
		if (!s_t.empty())
		{
			TreeNode* temp = s_t.top();
			cout << temp->val << endl;
			p = temp->right;
			s_t.pop();
		}
	}
}

//树的前序遍历

void qianxu(TreeNode* root)
{
	TreeNode* p = root;
	stack<TreeNode*> s_t;
	while (!s_t.empty() || p != NULL)
	{
		while (p != NULL)
		{
			s_t.push(p);
			cout << p->val << endl;
			p = p->left;
		}
		if (!s_t.empty())
		{
			TreeNode* temp = s_t.top();
			//cout << temp->val << endl;
			p = temp->right;
			s_t.pop();
		}
	}
}

一些拓展
求到目标节点的路径,输出的是从当前节点到根节点的路径,包含当前节点的

void houxu_tuozhan(TreeNode* root)
{
	int top = -1;
	int flag[10000];	
	stack<TreeNode*> s_t;
	TreeNode* p = root;	
	while (!s_t.empty() || p != NULL)
	{
		while (p != NULL)
		{
			++top;
			s_t.push(p);
			flag[top] = 0;
			p = p->left;
		}
		//这里不需要的
		while (top >= 0 && flag[top] == 1)//只有当右节点被访问到了才能访问根
		{
			if (s_t.top()->val == 5)//如果相等的话就把 当前栈中的数据出去
			{
				while (!s_t.empty())
				{
					cout << s_t.top()->val << endl;
					s_t.pop();
				}
				return;
			}
			--top;
			s_t.pop();
		}
		if (!s_t.empty())
		{
			TreeNode* temp = s_t.top();
			p = temp->right;
			flag[top] = 1;
		}
	}
}

求两个在树上的节点的最近公共祖先(递归)

TreeNode* qiu_liangge(TreeNode* root,int target1,int target2)
{
	//对于这种题目怎么计算因为:求两个存在在树中的节点最低公共祖先
	TreeNode* p = root;
	if (root == NULL)
		return NULL;
	if (root->val == target1)
		return root;
	if (root->val == target2)
		return root;
	TreeNode* left_1 = qiu_liangge(root->left, target1, target2);
	TreeNode* right_1 = qiu_liangge(root->right, target1, target2);
	if (left_1 == NULL&&right_1 == NULL)
		return NULL;
	if (left_1 != NULL&&right_1 != NULL)
		return root;
	if (left_1 == NULL)
		return right_1;
	if (right_1 == NULL)
		return left_1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值