由前序和中序序列构建二叉树
来源:互联网 发布:419什么意思网络语言 编辑:程序博客网 时间:2024/05/12 10:47
根据前序遍历和中序遍历的特点,前序序列的第一个是树的根结点,然后再中序序列中找到根节点,左边为左子树,右边右子树,然后递归建立各个子树。
代码如下:
#include <iostream>#include <algorithm>using namespace std;struct TNode{ int m_val; TNode* m_left; TNode* m_right;};TNode* ConstructTree(int *preorderStart, int *preorderEnd, int *inorderStart, int *inorderEnd){ int rootVal = *preorderStart; TNode* root = new TNode(); root->m_val = rootVal; root->m_left = root->m_right = NULL; //search for root in inorder int* rootPos = NULL; for (rootPos = inorderStart; rootPos <= inorderEnd; rootPos++) { if (*rootPos == rootVal) { break; } } if (rootPos > inorderEnd) { cout << "Wrong data" << endl; } if (preorderStart == preorderEnd) { if (inorderStart == inorderEnd && *preorderStart == * inorderStart) { return root; } else{ cout << "Wrong data" << endl; } } int leftlength = rootPos - inorderStart; if (leftlength > 0) { root->m_left = ConstructTree(preorderStart + 1, preorderStart + leftlength, inorderStart, rootPos - 1); } if (leftlength < preorderEnd - preorderStart) { root->m_right = ConstructTree(preorderStart + leftlength + 1, preorderEnd, rootPos + 1, inorderEnd); } return root;}TNode* Construct(int* preorder, int* inorder, int length){ if (preorder == NULL || inorder == NULL || length <= 0) { return NULL; } return ConstructTree(preorder, preorder + length - 1, inorder, inorder + length - 1);}int main(int argc, const char * argv[]){ int preorder[] {1, 2, 4, 7, 3, 5, 6, 8}; int inorder[] {4, 7, 2, 1, 5, 3, 8, 6}; TNode* t = Construct(preorder, inorder, 8); return 0;}
0 0
- 由前序和中序序列构建二叉树
- 由二叉树的前序序列和中序序列构建二叉树
- [LeetCode] 由前序和中序序列,构建二叉树
- 中序和前序序列构建二叉树
- 由二叉树的前序遍历序列和中序遍历序列求后序遍历序列
- 由前序序列和中序序列来重构二叉树
- 由前序遍历序列和中序遍历序列重建二叉树
- lintcode 前序序列和中序序列构建二叉树
- 由前序和中序遍历构建一颗二叉树
- 题目:1385 由前序和中序构建二叉树
- 由前序遍历和中序遍历重新构建二叉树
- 剑指offer-重建二叉树 由前序和中序遍历序列建树
- 已知二叉树的前序和中序序列,构建二叉树并求后序序列,java实现。
- 由前序遍历和中序遍历重建二叉树(前序序列:1 2 3 4 5 6
- 面试题6:根据前序和中序序列构建二叉树(Leetcode-106)
- 根据树的后序和中序序列或者前序和中序序列构建二叉树,
- Java实现由前序序列和中序序列重建二叉树,并后序输出。
- 树——由中序和前序,中序和后序序列重建二叉树
- sqlalchemy学习日志
- Toj 3345/hdu 1281 Chinese Chess 二分图匹配
- Duilib Demo 编译报错:(error C2371: “IDispatchEx”: 重定义;不同的基类型)
- OCP 1Z0 053 168
- linux(ubuntu)下基于java的在线音乐仿qq播放器,
- 由前序和中序序列构建二叉树
- 7.12-2014新生归来赛
- mysql错误及解决(1)
- 《Programming in Lua 3》读书笔记(十二)
- C#调用C++ DLL简析(一)——生成非托管dll
- metasploit + openvas
- 汉字首字母转化
- 海盗分赃
- 天嵌E9平台下进行USB Wifi模块RT3070驱动的移植