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

【LeetCode】Construct Binary Tree from Inorder and Postorder Traversal

时间:2014-11-30 15:20:40      阅读:128      评论:0      收藏:0      [点我收藏+]

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

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.

 

根据定义,后序遍历postorder的最后一个元素为根。

由于元素不重复,通过根可以讲中序遍历inorder划分为左子树和右子树。

递归下去即可求解。

/**
 * 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) {
        return Helper(inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1);
    }
    TreeNode *Helper(vector<int> &inorder, int begin1, int end1, vector<int> &postorder, int begin2, int end2)
    {
        if(begin1 > end1)
            return NULL;
        else if(begin1 == end1)
            return new TreeNode(inorder[begin1]);
        else
        {
            //in posterorder, root is the last visitor 
            TreeNode* root = new TreeNode(postorder[end2]);
            int ind;
            for(ind = begin1; ind <= end1; ind ++)
            {
                if(inorder[ind] == postorder[end2])
                    break;
            }
            //inorder[ind] is the root value in inorder
            //left has ind-begin1 nodes
            root->left = Helper(inorder, begin1, ind-1, postorder, begin2, begin2+ind-begin1-1);
            //right has end1-ind nodes
            root->right = Helper(inorder, ind+1, end1, postorder, end2-end1+ind, end2-1);
            return root;
        }
    }
};

bubuko.com,布布扣

【LeetCode】Construct Binary Tree from Inorder and Postorder Traversal

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

原文地址:http://www.cnblogs.com/ganganloveu/p/4133059.html

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