[剑指offer]8.重建二叉树
生活随笔
收集整理的這篇文章主要介紹了
[剑指offer]8.重建二叉树
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重復的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹并輸出它的后序遍歷序列。
代碼
/*--------------------------------------- * 日期:2015-07-20 * 作者:SJF0115 * 題目: 8.重建二叉樹 * 結果:AC * 網址:http://www.nowcoder.com/books/coding-interviews/8a19cbe657394eeaac2f6ea9b0f6fcf6?rp=1 * 來源:劍指Offer * 博客: -----------------------------------------*/ #include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std;struct TreeNode{int val;TreeNode *left;TreeNode *right;TreeNode(int x):val(x),left(nullptr),right(nullptr){} };class Solution{ public:struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) {int size = pre.size();if(size == 0){return nullptr;}//ifreturn PreInBuildTree(pre,in,0,0,size);} private:TreeNode* PreInBuildTree(vector<int> preorder,vector<int> inorder,int preIndex,int inIndex,int size){if(size == 0){return nullptr;}//if// 根節點TreeNode* root = new TreeNode(preorder[preIndex]);// 尋找根節點在中序遍歷數組的下標int index = 0;for(int i = 0;i < size;++i){// 注意:inorder[inIndex+i]if(preorder[preIndex] == inorder[inIndex+i]){index = inIndex+i;break;}//if}//for// 左子樹個數int leftSize = index - inIndex;// 右子樹個數int rightSize = size - leftSize - 1;// 左子樹root->left = PreInBuildTree(preorder,inorder,preIndex+1,inIndex,leftSize);// 右子樹root->right = PreInBuildTree(preorder,inorder,preIndex+1+leftSize,index+1,rightSize);return root;} };void PostOrder(TreeNode* root){if(root){PostOrder(root->left);PostOrder(root->right);cout<<root->val<<endl;}//if }int main(){Solution s;vector<int> preOrder = {1,2,4,7,3,5,6,8};vector<int> inOrder = {4,7,2,1,5,3,8,6};TreeNode* root = s.reConstructBinaryTree(preOrder,inOrder);PostOrder(root);return 0; } 與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的[剑指offer]8.重建二叉树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: kingshard--一个支持shard
- 下一篇: js 1 声明变量 数据类型