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

Construct Binary Tree from Preorder and Inorder Traversal

时间:2016-11-12 16:49:58      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:bre   struct   root   cto   log   dtree   efi   i++   order   

Construct Binary Tree from Preorder and Inorder Traversal

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

分析: 根据前序遍历和中序遍历构造一棵树,递归求解即可

/**
 * 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:
    void Build(int l1,int l2, int r1,int r2, const vector<int>& pre, const vector<int> & in, TreeNode*& root){
        root = new TreeNode(pre[l1]);
        int i;
        for(i=r1; i<=r2; i++)
            if(in[i]==root->val)
                break;
        if(i==r1)
            root->left=nullptr;
        else
            Build(l1+1, l1+i-r1,r1, i-1 ,pre,in, root->left);
        if(i==r2)
            root->right=nullptr;
        else
            Build(l1+i-r1+1, l2, i+1, r2, pre, in, root->right);
        return;
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        if(preorder.size()==0 && inorder.size()==0)
            return nullptr;
        TreeNode* root;
        Build(0,preorder.size()-1, 0, inorder.size()-1, preorder, inorder, root);
        return root;
    }
};

 

Construct Binary Tree from Preorder and Inorder Traversal

标签:bre   struct   root   cto   log   dtree   efi   i++   order   

原文地址:http://www.cnblogs.com/willwu/p/6056730.html

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