首页 > 其他 > 详细

【leetocde】 105. Construct Binary Tree from Preorder and Inorder Traversal

时间:2016-06-25 22:54:37      阅读:252      评论:0      收藏:0      [点我收藏+]

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

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

 

Subscribe to see which companies asked this question

 
 
递归就可以了。
 
#include<algorithm>
using namespace std;
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        if(preorder.size()==0||inorder.size()==0||find(inorder.begin(),inorder.end(),preorder[0])==inorder.end())
            return NULL;
        auto rootindex=find(inorder.begin(),inorder.end(),preorder[0]);
        TreeNode *root = new TreeNode(preorder[0]);
        vector<int> subleft,subright;
        preorder.erase(preorder.begin());
        if(rootindex!=inorder.begin())
            subleft.insert(subleft.begin(),inorder.begin(),rootindex);
        if(rootindex!=inorder.end()-1)
            subright.insert(subright.begin(),rootindex+1,inorder.end());
           root->left=buildTree(preorder,subleft);
           root->right=buildTree(preorder,subright);
           return root;
    }
};

 

【leetocde】 105. Construct Binary Tree from Preorder and Inorder Traversal

原文:http://www.cnblogs.com/LUO77/p/5616963.html

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