满二叉树的题(先序求后序,后序建树等等)

本文介绍如何从满二叉树的后序数组恢复满二叉树,并提供了一个使用递归深度优先搜索实现的示例代码。同时,还展示了如何仅通过已知的先序遍历序列来得到后序遍历的结果。
摘要由CSDN通过智能技术生成

这个代码是给你满二叉树的后序数组,恢复成满二叉树,如果还要求什么遍历顺序,也可以直接在新建的树上遍历即可。

这里有篇博客还不错,别人写的,只看看思想就行,代码就不用看了。点击查看!

代码:

#include <iostream>
#include <thread>
#include <string>
#include <chrono>
#include <future>
# include <cmath>
# include <vector>
#include <Windows.h>
 
using namespace std;

int deep=0;

struct node{
	int val;
	node* left,*right;
	node(node* a,node* b):left(a),right(b){}
};
 
node* dfs(vector<int>& arr,int step,int& idx){
	if(step>deep) return NULL;
	node* head = new node(NULL,NULL);
	head->left = dfs(arr,step+1,idx);
	head->right = dfs(arr,step+1,idx);
	head->val = arr[idx++];
	return head;
}

void dfs_op(node* head){
	if(head==NULL) return ;
	cout<<head->val<<endl;
	dfs_op(head->left);
	dfs_op(head->right);
	return ;
}
int main()
{
	int n =7;

	vector<int> arr{1,2,3,4,5,6,7};

	deep = log(n)/log(2)+1;
	int idx = 0;
	node* head = dfs(arr,1,idx);

	dfs_op(head);
	system("pause");
	return 0;
}

已知满二叉树的先序遍历,求其后序遍历
(这个是没有建立树的这一步骤,是直接求出来的)
代码:

stack<int> _sta;    //全局栈,用来记录后序遍历。

//已知满二叉树的先序遍历,求其后序遍历
void PostWithPre(int pre[],int beg,int _end)
{
        int length = _end - beg;

        if(length >= 1)
        {
            _sta.push(pre[beg]);

            beg = (length/2+1) + beg;

            PostWithPre(pre,beg,_end);

            beg = beg - (length/2);
            _end = _end - (length/2);

            PostWithPre(pre,beg,_end);

        }
        else
            _sta.push(pre[beg]);
}
根据遍历(Preorder)、中遍历(Inorder)和后序遍历(Postorder)构建二叉树是一种常见的树形结构构造算法,特别是对于已知节点顺的情况。以下是步骤: 1. **遍历(Preorder)**:根节点 -> 左子树 -> 右子树。遍历给出的是根节点的值,然后是左子树和右子树的遍历结果。 2. **中遍历(Inorder)**:左子树 -> 根节点 -> 右子树。中遍历可以用于确定每个节点的位置,因为它按照左子树-根-右子树的顺访问。 3. **后序遍历(Postorder)**:左子树 -> 右子树 -> 根节点。后序遍历最后得到根节点的值,这对于重建树非常有用,因为可以根据左右子树构建子树,最后放置根节点。 要构建树,通常采取以下步骤: - 初始化一个空树或根节点。 - 使用当前遍历列的第一个元素作为新树的根节点。 - 如果还有剩余的遍历列,对前遍历剩余部分执行上述过程,作为根节点的左子树。 - 对中遍历剩余部分执行相同过程,作为根节点的右子树。 下面是简单的伪代码示例: ```python def buildTree(preOrder, inOrder): if not preOrder or not inOrder: return None rootValue = preOrder[0] # 根据找到根节点 rootIndex = find(inOrder, rootValue) # 找到根节点在中数组中的位置 # 创建根节点 root = TreeNode(rootValue) # 分别处理左子树和右子树 root.left = buildTree(preOrder[1:rootIndex], inOrder[:rootIndex]) root.right = buildTree(preOrder[rootIndex + 1:], inOrder[rootIndex + 1:]) return root def find(arr, target): # 找到目标值在数组中的索引 # 实际实现依赖于数组搜索算法(如二分查找) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值