leetcode:二叉树之Construct Binary Tree from Inorder and Postorder Traversal

来源:互联网 发布:asp连接数据库 教程 编辑:程序博客网 时间:2024/05/26 07:29

leetcode:二叉树之Construct Binary Tree from Inorder and Postorder Traversal

题目:

Given inorder and postorder traversal of a tree, construct the binary tree.

Note: You may assume that duplicates do not exist in the tree.

即,根据给定的二叉树的中序遍历与后序遍历,构建二叉树

例如:

一未知的二叉树的中序遍历为:[3,2,4,1,5,6],其后序遍历为:[3,4,2,6,5,1]

由中序遍历与后序遍历我们可以得到二叉树为:


我们根据上图可以得到其前序遍历为:[1,2,3,4,5,6],我们利用其前序遍历来验证二叉树是否构建成功。

C++实现:

#include <iostream>#include <vector>using namespace std;struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode(int x) : val(x), left(NULL), right(NULL) { }};template<typename BidiIt>TreeNode* buildTree(BidiIt in_first, BidiIt in_last,BidiIt post_first, BidiIt post_last);TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {return buildTree(begin(inorder), end(inorder),begin(postorder), end(postorder));}template<typename BidiIt>TreeNode* buildTree(BidiIt in_first, BidiIt in_last,BidiIt post_first, BidiIt post_last){if (in_first ==in_last)return NULL;if (post_first == post_last) return NULL;const auto val = *prev(post_last);TreeNode* root = new TreeNode(val);auto in_root_pos = find(in_first, in_last, val);auto left_size = distance(in_first, in_root_pos);auto post_left_last = next(post_first, left_size);root->left = buildTree(in_first, in_root_pos, post_first, post_left_last);root->right = buildTree(next(in_root_pos), in_last, post_left_last,prev(post_last));return root;}void preorderTraverse(TreeNode* &T){   if(T)//当结点不为空的时候执行{  cout<<T->val;preorderTraverse(T->left);//  preorderTraverse(T->right);  }  else cout<<"";  }int main(){int inorder[6]={3,2,4,1,5,6};int postorder[6]={3,4,2,6,5,1};     vector<int>in(inorder,inorder+6);vector<int>post(postorder,postorder+6);TreeNode* Tree(0);Tree=buildTree(in, post);preorderTraverse(Tree);cout<<endl;    return 0;}
测试结果:



0 0
原创粉丝点击