码迷,mamicode.com
首页 > 其他好文 > 详细

Construct Binary Tree from Inorder and Postorder Traversal

时间:2014-11-24 11:47:33      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   for   

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

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

 

C++实现代码:

#include<iostream>
#include<new>
#include<vector>
using namespace std;

//Definition for binary tree
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        TreeNode *root=NULL;
        root=build(inorder.begin(),inorder.end(),postorder.begin(),postorder.end());
        return root;
    }
    TreeNode *build(vector<int>::iterator ibegin,vector<int>::iterator iend,vector<int>::iterator pbegin,vector<int>::iterator pend)
    {
        TreeNode *root=NULL;
        if(pbegin==pend||ibegin==iend)
            return NULL;
        auto it=ibegin;
        auto tmp=pend-1;
        while(it!=iend)
        {
            if(*it==*tmp)
                break;
            it++;
        }
        root=new TreeNode(*it);
        int len=it-ibegin;
        root->left=build(ibegin,it,pbegin,pbegin+len);
        root->right=build(it+1,iend,pbegin+len,pend-1);
        return root;
    }
    void preorder(TreeNode *root)
    {
        if(root)
        {
            cout<<root->val<<" ";
            preorder(root->left);
            preorder(root->right);
        }
    }
    void inorder(TreeNode *root)
    {
        if(root)
        {
            inorder(root->left);
            cout<<root->val<<" ";
            inorder(root->right);
        }
    }
    void postorder(TreeNode *root)
    {
        if(root)
        {
            postorder(root->left);
            postorder(root->right);
            cout<<root->val<<" ";
        }
    }
};

int main()
{
    vector<int> posorder={4,5,2,6,7,3,1};
    vector<int> inorder={4,2,5,1,6,3,7};
    Solution s;
    TreeNode *root=s.buildTree(inorder,posorder);
    s.preorder(root);
    cout<<endl;
    s.inorder(root);
    cout<<endl;
    s.postorder(root);
    cout<<endl;
}

运行结果:

bubuko.com,布布扣

Construct Binary Tree from Inorder and Postorder Traversal

标签:style   blog   http   io   ar   color   os   sp   for   

原文地址:http://www.cnblogs.com/wuchanming/p/4118050.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!