首页 > 其他 > 详细

[LeetCode] Construct Binary Tree from Inorder and Postorder Traversal

时间:2014-03-24 07:06:20      阅读:388      评论:0      收藏:0      [点我收藏+]

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

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

Solution:

bubuko.com,布布扣
/**
 * 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 *built(vector<int> &inorder, vector<int> &postorder, int in_start, int in_end, int post_start, int post_end)
    {
        if(in_start > in_end || post_start > post_end) 
            return NULL;
        TreeNode *curRoot = new TreeNode(postorder[post_end]);
        int rootIndex = -1;
        for(int i = in_end;i >= in_start;i--)
        {
            if(inorder[i] == postorder[post_end])
            {
                rootIndex = i;
                break;
            }
        }
        if(rootIndex == -1) return NULL;
        int leftNum = rootIndex - in_start;
        curRoot -> left = built(inorder, postorder, in_start, rootIndex - 1, post_start, post_start + leftNum - 1);
        curRoot -> right = built(inorder, postorder, rootIndex + 1, in_end, post_start + leftNum, post_end - 1);
        return curRoot;
    }

    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        return built(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1); 
    }
};
bubuko.com,布布扣

[LeetCode] Construct Binary Tree from Inorder and Postorder Traversal,布布扣,bubuko.com

[LeetCode] Construct Binary Tree from Inorder and Postorder Traversal

原文:http://www.cnblogs.com/changchengxiao/p/3619739.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!