C++根据树的前序遍历,中序遍历写出后序遍历

数据结构(树的遍历)

功能实现:根据前序遍历,中序遍历,写出后序遍历。


#include <iostream>
// 这里就简单写个数组模拟树
int preArray[] = { 1,2,3,4,5,6 };
int inArray[] = { 3,2,4,1,6,5 };
int postArray[6] = { 0 };

//根据前序遍历第一个位置,为根节点,中序遍历根节点的左侧为左子树,右侧为右子树,递归分治解决。
void createPost(int preL, int inL, int postL, int n)
{
	if (n == 0) return;
	if (n == 1)
	{
		postArray[postL] = preArray[preL];
		return;
	}

	int root = preArray[preL];
	postArray[postL + n - 1] = root;
	int i = 0;
	for (; i < n; i++)
	{
		if (inArray[inL + i] == root)
			break;
	}

	int Ln = i;  
	int Rn = n - Ln - 1;
	createPost(preL + 1, inL, postL, Ln);
	createPost(preL + Ln + 1, inL + Ln + 1, postL + Ln, Rn);
}

void main()
{
	createPost(0, 0, 0, 6);
	for (auto& temp : postArray)
	{
		std::cout << temp << ' ';
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
的深度优先遍包括和后,它们的遍规则分别为: (Preorder traversal):遍规则为【DLR | 即当结点, 左孩子, 右孩子】。 (Inorder Traversal):遍规则为【LDR | 即左孩子, 当结点, 右孩子】。 后(Postorder Traversal):遍规则为【LRD | 即左孩子, 右孩子, 当结点】。 因此,深度优先遍不是和后的统称,而是包括了这三种遍方式。 下面是C++代码实现: 递归实现: ```c++ // void preorder(TreeNode* root) { if (root == nullptr) { return; } cout << root->val << " "; preorder(root->left); preorder(root->right); } // void inorder(TreeNode* root) { if (root == nullptr) { return; } inorder(root->left); cout << root->val << " "; inorder(root->right); } // 后 void postorder(TreeNode* root) { if (root == nullptr) { return; } postorder(root->left); postorder(root->right); cout << root->val << " "; } ``` 非递归实现: ```c++ // void preorder(TreeNode* root) { if (root == nullptr) { return; } stack<TreeNode*> s; s.push(root); while (!s.empty()) { TreeNode* node = s.top(); s.pop(); cout << node->val << " "; if (node->right != nullptr) { s.push(node->right); } if (node->left != nullptr) { s.push(node->left); } } } // void inorder(TreeNode* root) { if (root == nullptr) { return; } stack<TreeNode*> s; TreeNode* node = root; while (node != nullptr || !s.empty()) { while (node != nullptr) { s.push(node); node = node->left; } node = s.top(); s.pop(); cout << node->val << " "; node = node->right; } } // 后 void postorder(TreeNode* root) { if (root == nullptr) { return; } stack<TreeNode*> s1, s2; s1.push(root); while (!s1.empty()) { TreeNode* node = s1.top(); s1.pop(); s2.push(node); if (node->left != nullptr) { s1.push(node->left); } if (node->right != nullptr) { s1.push(node->right); } } while (!s2.empty()) { cout << s2.top()->val << " "; s2.pop(); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值