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

[leetcode] construct-binary-tree-from-preorder-and-inorder-

时间:2017-06-23 23:53:48      阅读:386      评论:0      收藏:0      [点我收藏+]

标签:ons   return   ++   rsa   title   ica   describe   and   tle   

题目描述

 

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

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

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    
    
    void ConstructTree(TreeNode *&tree, vector<int> &preorder, int prebegin, int preend, vector<int> &inorder, int inbegin, int inend)
    {
        if(prebegin > preend || inbegin > inend)
            return;
        int i;
        int mid = preorder[prebegin];
        for(i = inbegin; i <= inend; i++)
        {
            if(inorder[i] == mid)
                break;
        }
        tree = new TreeNode(mid);
        ConstructTree(tree->left, preorder, prebegin+1, prebegin+i-inbegin, inorder, inbegin, i-1);
        ConstructTree(tree->right, preorder, prebegin+i+1-inbegin, preend, inorder, i+1, inend);
    }
    
    
    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) 
    {
        if(preorder.size() == 0 || inorder.size() == 0)
            return NULL;
        TreeNode *tree = NULL;
        
        ConstructTree(tree, preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
        
        return tree;
    }
};

 

[leetcode] construct-binary-tree-from-preorder-and-inorder-

标签:ons   return   ++   rsa   title   ica   describe   and   tle   

原文地址:http://www.cnblogs.com/htzhang0908/p/7071959.html

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