首页 > 代码库 > 前序遍历和中序遍历树构造二叉树

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

例子

题目来自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 = http://www.mamicode.com/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;
    }
};
<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

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