【剑指offer】如何通过先序遍历与中序遍历重建二叉树

来源:互联网 发布:微商发图软件 编辑:程序博客网 时间:2024/03/30 10:29

要用代码实现重建二叉树的话,我们必须了解先序遍历与中序遍历确定二叉树的过程,如给定先序遍历序列为 1, 2, 4, 7, 3, 5, 6, 8,中序遍历序列为4, 7, 2, 1, 5, 3, 8, 6。

其主要思想就是先序序列确定根节点,中序遍历确定左右子树,解析如下:


(图太丑- -。意思到了就行哈)

由图我们可以看出来,这实质就是一个递归问题,退出递归的限定条件我们可以用左右子树的长度

代码如下:

/*通过中序遍历与前序遍历重建二叉树*/#include<iostream>#include<cassert>using namespace std;struct BinaryTreeNode{BinaryTreeNode* _left;BinaryTreeNode* _right;int _data;BinaryTreeNode(): _left(NULL), _right(NULL), _data(-1){}BinaryTreeNode(int x): _left(NULL), _right(NULL), _data(x){}};class BinaryTree{typedef BinaryTreeNode Node;public:BinaryTree():_root(NULL){}void ReCreatTree(int *POrderArray,int *IOrderArray,size_t size){assert(POrderArray);assert(IOrderArray);assert(size);_ReCreatTree(POrderArray, IOrderArray, size,_root);}protected:void _ReCreatTree(int *POrderArray, int *IOrderArray, size_t size,Node*& root){if (size < 1)return;root = new Node(POrderArray[0]);int* index = IOrderArray;while (*index != root->_data)++index;_ReCreatTree(POrderArray + 1, IOrderArray, index - IOrderArray, root->_left);_ReCreatTree(POrderArray + (index - IOrderArray) + 1, index + 1, size - (index - IOrderArray) - 1, root->_right);}protected:Node* _root;};int main(){BinaryTree t;int POrderArray[] = { 1, 2, 4, 7, 3, 5, 6, 8 };int IOrderArray[] = { 4, 7, 2, 1, 5, 3, 8, 6 };t.ReCreatTree(POrderArray, IOrderArray, sizeof(POrderArray) / sizeof(POrderArray[0]));system("pause");return 0;}
如有不足希望指正

1 0
原创粉丝点击