标签:重建二叉树 节点 pac 遍历 microsoft png 基本 alt util
#include <iostream> #include <algorithm> #include "string.h" #include "stdio.h" #include <vector> #include <deque> #include <stack> #include <queue> #include<map> #include<utility> #include "math.h" using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Tree{ public: void PrintTree(TreeNode* pRoot) { if(pRoot == NULL) return; int level = 0; int index = 0; int globle = 0; queue<TreeNode*> queue; queue.push(pRoot); while(!queue.empty()) { TreeNode* pNode = queue.front(); cout<<pNode->val<<" "; queue.pop(); if(pNode->left) { queue.push(pNode->left); } if(pNode->right) { queue.push(pNode->right); } } } }; class Solution { public: TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { if(pre.size() == NULL || pre.size() == NULL || pre.size()!=vin.size()) return NULL; vector<int> pre_left; vector<int> pre_right; vector<int> vin_left; vector<int> vin_right; int index = 0; for(int i=0;i<vin.size();i++) { if(vin[i] == pre[0]) { index = i; break; } } for(int i=0;i<vin.size();i++) { if(i<index) { vin_left.push_back(vin[i]); pre_left.push_back(pre[i+1]); } if(i>index) { vin_right.push_back(vin[i]); pre_right.push_back(pre[i]); } } TreeNode* pRoot = new TreeNode(pre[0]); pRoot->left = reConstructBinaryTree(pre_left,vin_left);//递归左子树 pRoot->right = reConstructBinaryTree(pre_right,vin_right);//递归右子树 return pRoot; } }; int main() { vector<int> pre; pre.push_back(1); pre.push_back(2); pre.push_back(4); pre.push_back(7); pre.push_back(3); pre.push_back(5); pre.push_back(6); pre.push_back(8); vector<int> vin; vin.push_back(4); vin.push_back(7); vin.push_back(2); vin.push_back(1); vin.push_back(5); vin.push_back(3); vin.push_back(8); vin.push_back(6); Solution solution; Tree tree; TreeNode* p = solution.reConstructBinaryTree(pre,vin); tree.PrintTree(p); }
标签:重建二叉树 节点 pac 遍历 microsoft png 基本 alt util
原文地址:http://www.cnblogs.com/omelet/p/6648345.html