根据先序和中序序列重建二叉树
生活随笔
收集整理的這篇文章主要介紹了
根据先序和中序序列重建二叉树
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#include "stdafx.h"
#include <iostream>
#include <exception>
#include <stack>
using namespace std;/*重建二叉樹
題目:輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹.假設輸入的前序遍歷和中序遍歷的結果中都不含重復的數字.例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建出圖所示的二叉樹并輸出它的頭結點。二叉樹結點的定義如下:
*/struct BinaryTreeNode
{int m_nValue;BinaryTreeNode* m_pLeft;BinaryTreeNode* m_PRight;
};BinaryTreeNode* ConstructConre(int* startPreorder,int* endPreorder,int* startInorder,int* endInorder)
{int rootValue = startPreorder[0];BinaryTreeNode* root = new BinaryTreeNode();root->m_nValue = rootValue;root->m_pLeft = root->m_PRight = NULL;if(startPreorder == endPreorder){if(startInorder == endInorder && *startPreorder ==*startInorder)return root;elsethrow std::exception("invalid input");}//在中序遍歷中找到根結點的值int* rootInorder = startInorder;while(rootInorder <= endInorder&& *rootInorder !=rootValue)++ rootInorder;if(rootInorder ==endInorder && *rootInorder != rootValue)throw std::exception("Invalid input.");int leftLength = rootInorder - startInorder;int *leftPreorderEnd = startPreorder +leftLength;if(leftLength >0){//構建左子樹root->m_pLeft = ConstructConre(startPreorder+1,leftPreorderEnd,startInorder,rootInorder -1);}if(leftLength<endPreorder - startPreorder){//構建右子樹root->m_PRight = ConstructConre(leftPreorderEnd +1,endPreorder,rootInorder+1,endInorder);}return root;
}BinaryTreeNode* Construct(int *preOrder,int* inOrder,int length)
{if(preOrder==NULL||inOrder==NULL||length<=0){return NULL;}return ConstructConre(preOrder,preOrder+length-1,inOrder,inOrder+length-1);
}
int _tmain(int argc, _TCHAR* argv[])
{ return 0 ;
}
?
轉載于:https://www.cnblogs.com/crazycodehzp/p/3556863.html
總結
以上是生活随笔為你收集整理的根据先序和中序序列重建二叉树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 5.1.2全景声音箱摆位_全景声音响系统
- 下一篇: 移动互联网APP测试流程及测试点(转载)