标签:style blog http color strong os
题目:
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
说明:
1)实现与根据先序和中序遍历构造二叉树相似,题目参考请进
实现:
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { 13 return creatTree(inorder.begin(),inorder.end(),postorder.begin(),postorder.end()); 14 } 15 private: 16 template<typename InputIterator> 17 TreeNode *creatTree(InputIterator in_beg,InputIterator in_end,InputIterator post_beg,InputIterator post_end) 18 { 19 if(in_beg==in_end||post_beg==post_end) return nullptr; //空树 20 TreeNode *root=new TreeNode(*(post_end-1)); 21 auto inRootPos=find(in_beg,in_end,root->val);//中序遍历中找到根节点,返回迭代指针 22 int leftlen=distance(in_beg,inRootPos);//中序遍历起点指针与找到的根节点指针的距离 23 root->left=creatTree(in_beg,inRootPos,post_beg,next(post_beg,leftlen));//递归构建左子数 24 root->right=creatTree(next(inRootPos),in_end,next(post_beg,leftlen),post_end-1);//递归构建右子树 25 return root; 26 } 27 };
leetcode题解:Construct Binary Tree from Inorder and Postorder Traversal(根据中序和后序遍历构造二叉树),布布扣,bubuko.com
leetcode题解:Construct Binary Tree from Inorder and Postorder Traversal(根据中序和后序遍历构造二叉树)
标签:style blog http color strong os
原文地址:http://www.cnblogs.com/zhoutaotao/p/3833324.html