剑指offer 面试题6:重建二叉树
重建二叉树
题目
输入某二叉树的前序遍历和中序遍历,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含有重复的数字。
例如,前序遍历序列:{1,2,3,7,3,5,6,8},中序遍历序列:{4,7,2,1,5,3,8,6}
答案
前序遍历:
前序遍历首先访问根结点然后遍历左子树,最后遍历右子树。在遍历左、右子树时,仍然先访问根结点,然后遍历左子树,最后遍历右子树。
中序遍历:
中序遍历首先遍历左子树,然后访问根结点,最后遍历右子树。在遍历左、右子树时,仍然先遍历左子树,再访问根结点,最后遍历右子树。
#include <iostream> using namespace std; struct binary_tree_node{ int value; binary_tree_node* left; binary_tree_node* right; }; binary_tree_node* binary_tree_constuct(int* preorder, int* inorder, int length); int main() { int pre[8] = {1,2,4,7,3,5,6,8}; int in[8] = {4,7,2,1,5,3,8,6}; binary_tree_node* root = binary_tree_constuct(pre, in, 8); } binary_tree_node* construct_method(int* preorder, int* endpreorder, int* inorder, int* endinorder) { int root_value = preorder[0]; binary_tree_node* root = new binary_tree_node(); root->left = NULL; root->right = NULL; cout<<root_value<<" "; if(preorder == endpreorder && inorder == endinorder) return root; int* rootIndex = preorder; rootIndex++; while(*rootIndex != root_value && rootIndex < endpreorder) rootIndex++; int left_len = rootIndex - preorder; int* left_preorder_end = preorder + left_len; //left if(left_len > 0) { root->left = construct_method(preorder+1, left_preorder_end, inorder, rootIndex-1); } //right if(left_len < endpreorder - preorder) { root->right = construct_method(left_preorder_end+1, endpreorder, rootIndex+1, endinorder); } return root; } binary_tree_node* binary_tree_constuct(int* preorder, int* inorder, int length) { if(preorder == NULL || inorder == NULL || length <= 0) { return NULL; } return construct_method(preorder, preorder+length-1, inorder,inorder+length-1); }
本文 由 cococo点点 创作,采用 知识共享 署名-非商业性使用-相同方式共享 3.0 中国大陆 许可协议进行许可。欢迎转载,请注明出处:
转载自:cococo点点 http://www.cnblogs.com/coder2012
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!