标签:
Given inorder and postorder 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<algorithm> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; TreeNode *CreatTree(vector<int>::iterator in_begin, vector<int>::iterator in_end, vector<int>::iterator pos_begin, vector<int>::iterator pos_end ) { if (in_begin == in_end) return NULL; vector<int>::iterator Rootpos = pos_end-1; vector<int>::iterator Rootino = find(in_begin, in_end, *Rootpos); auto lenleft = distance(in_begin, Rootino); TreeNode *root = new TreeNode(*Rootpos); root->left = CreatTree(in_begin, Rootino, pos_begin, pos_begin + lenleft); root->right = CreatTree(Rootino + 1, in_end, pos_begin + lenleft, Rootpos); return root; } TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { if (inorder.empty()) return NULL; TreeNode *Root = new TreeNode(0); Root = CreatTree(inorder.begin(), inorder.end(), postorder.begin(), postorder.end()); return Root; }
Construct Binary Tree from Inorder and Postorder Traversal
标签:
原文地址:http://blog.csdn.net/li_chihang/article/details/44154209