标签:
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
#include<iostream> #include<vector> #include<map> #include<algorithm> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; TreeNode *CreatNode(vector<int>::iterator pre_begin, vector<int>::iterator pre_end, vector<int>::iterator ino_begin, vector<int>::iterator ino_end) { if (pre_begin == pre_end) return NULL; TreeNode* curnode = new TreeNode(*pre_begin); auto iter = find(ino_begin, ino_end, *pre_begin); int lenLeftTree = distance(ino_begin, iter); curnode->left = CreatNode( pre_begin + 1, pre_begin +1+ lenLeftTree, ino_begin, iter); curnode->right = CreatNode( pre_begin + 1+lenLeftTree, pre_end, iter+1,ino_end ); return curnode; } TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { if (preorder.empty()) return NULL; TreeNode* root = new TreeNode(0); root = CreatNode(preorder.begin(), preorder.end(), inorder.begin(), inorder.end()); return root; }
Construct Binary Tree from Preorder and Inorder Traversal
标签:
原文地址:http://blog.csdn.net/li_chihang/article/details/44151693