博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
重建二叉树
阅读量:2726 次
发布时间:2019-05-13

本文共 2686 字,大约阅读时间需要 8 分钟。

这里写图片描述

#define  _CRT_SECURE_NO_WARNINGS#include
using namespace std;struct BinaryTreeNode{ int _value; BinaryTreeNode* _left; BinaryTreeNode* _right; BinaryTreeNode(int value) :_value(value), _left(NULL), _right(NULL) {}};class BinaryTree{ typedef BinaryTreeNode Node;public: BinaryTree() :_root(NULL) {} void Construct(int *prevorder, int *inorder, int length) { if (prevorder == NULL || inorder == NULL || length <= 0) { return; } _root = _Construct(prevorder, prevorder + length - 1, inorder, inorder + length - 1); } void PrePrint() { _PrevPrint(_root); cout << endl; } void InPrint() { _InPrint(_root); cout << endl; }protected: Node* _Construct(int *startPrevorder, int *endPrevorder, int *startInorder, int *endInorder) { int rootValue = startPrevorder[0]; Node* root = new Node(rootValue); if (startPrevorder == endPrevorder) { if (startInorder == endInorder) { return root; } else { throw exception("Invalid input"); } } /* 在中序遍历中找根节点 */ int* rootInorder = startInorder; while (rootInorder <= endInorder && *rootInorder != rootValue) { ++rootInorder; } /*没找到,抛个异常*/ if (*rootInorder != rootValue) { throw exception("Invalid input"); } int leftLength = rootInorder - startInorder; int *leftPrevOrderEnd = startPrevorder + leftLength; if (leftLength > 0) {
//构建做子树 root->_left = _Construct(startPrevorder + 1, leftPrevOrderEnd, startInorder, rootInorder - 1); } if (leftLength < endPrevorder - startPrevorder) { //构建右子树 root->_right = _Construct(leftPrevOrderEnd + 1, endPrevorder, rootInorder + 1, endInorder); } return root; } void _InPrint(Node* root) { if (root == NULL) { return; } _PrevPrint(root->_left); cout << root->_value << " "; _PrevPrint(root->_right); } void _PrevPrint(Node* root) { if (root == NULL) { return; } cout << root->_value << " "; _PrevPrint(root->_left); _PrevPrint(root->_right); }private: Node* _root;};void test(){ int prev[] = { 1, 0, 4, 7, 3, 5, 6, 8 }; int in[] = { 4, 7, 2, 1, 5, 3, 8, 6 }; BinaryTree t; t.Construct(prev, in, 8); t.PrePrint(); t.InPrint();}int main(){ test(); system("pause"); return 0;}
你可能感兴趣的文章
Servlet实现文件上传
查看>>
Servlet实现文件上传
查看>>
request.getParameter() 、 request.getInputStream()和request.getReader() 使用体会
查看>>
request.getParameter() 、 request.getInputStream()和request.getReader() 使用体会
查看>>
BJUT数字图像处理作业
查看>>
BJUT数字图像处理作业
查看>>
JSP&Servlet学习笔记----第3章
查看>>
C语言写txt文件实例
查看>>
C语言读取txt文件实例
查看>>
C语言在txt文本后面添加字符串函数总结
查看>>
linux下将整数转化为字符串用法(itoa()函数,sprintf()函数)
查看>>
(转载)关于curses函数库的详细接介绍(linux环境下)
查看>>
Qt5.9布局管理器实例(QVBoxLayout,QHBoxLayout,QGridLayout)(一个简单的手写界面实例)
查看>>
[转]Myeclipse 快捷键大全
查看>>
[转]jsp-servlet技术
查看>>
[转] final、finally和finalize的区别是什么?
查看>>
发送和接收cookie
查看>>
javaBean属性对应注意点
查看>>
[转]java位操作符总结
查看>>
英文陷阱:Say uncle!叫声爷爷
查看>>