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

前序遍历和中序遍历树构造二叉树

时间:2017-08-08 23:12:08      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:tco   index   back   type   hid   containe   com   val   uil   

例子

题目来自LintCode, 给出中序遍历:[1,2,3]和前序遍历:[2,1,3]. 返回例如以下的树:

  2
 / 1   3

代码实现

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */


class Solution {
    /**
     *@param preorder : A list of integers that preorder traversal of a tree
     *@param inorder : A list of integers that inorder traversal of a tree
     *@return : Root of a tree
     */
public:

    int Get_root_index(vector<int> &preorder, vector<int> &inorder, int len)
    {
        int root_val = preorder[0];

        for(int i = 0; i < len; i++)
        {
            if(inorder[i] == root_val)
                return i;
        }

        return -1;
    }

    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
        // write your code here

        int pre_len = preorder.size();
        int in_len  = inorder.size();

        if(pre_len <= 0 && in_len <= 0)
                return NULL;

        int RootValue = preorder[0];
        TreeNode *root = new TreeNode();
        root->val = RootValue;


        if(pre_len == 1 && in_len == 1)
            return root;

        int index = Get_root_index(preorder, inorder, pre_len);

        vector<int> left_Preorder, left_Inorder, right_Preorder, right_Inorder;

        for(int i = 0; i < index; i ++)
        {
            left_Preorder.push_back(preorder[i+1]);
            left_Inorder.push_back(inorder[i]);
        }

        for(int i = index + 1; i < pre_len; i ++)
        {
            right_Preorder.push_back(preorder[i]);
        }

        for(int i = index + 1; i < in_len; i ++)
        {
            right_Inorder.push_back(inorder[i]);
        }

        root->left = buildTree(left_Preorder, left_Inorder);
        root->right = buildTree(right_Preorder, right_Inorder);

        return root;
    }
};

前序遍历和中序遍历树构造二叉树

标签:tco   index   back   type   hid   containe   com   val   uil   

原文地址:http://www.cnblogs.com/brucemengbm/p/7309148.html

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