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

Construct Binary Tree from Preorder and Inorder Traversal

时间:2015-06-20 15:37:46      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:

Description:

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

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

Code:

TreeNode * buildTree(vector<int>& preorder, int preBegin, int preEnd, vector<int>& inorder, int inBegin, int inEnd)
 {
    TreeNode*root =NULL;

    if (preEnd >= preBegin)
    {
        root = new TreeNode(preorder[preBegin]);
        int n = inEnd-inBegin+1;
        int rootIndex = 0;
        for (int i = inBegin; i <= inEnd; ++i)
        {
            if (inorder[i] == preorder[preBegin])
            {
                rootIndex = i;
                break;
            }
        }
        
        if (rootIndex!=inBegin)
        {
            root->left = buildTree(preorder, preBegin+1, preBegin+(rootIndex-inBegin), inorder, inBegin, rootIndex-1);
        }
        if (rootIndex!=inEnd)
        {
            root->right = buildTree(preorder, preBegin+1+(rootIndex-inBegin), preEnd, inorder, rootIndex+1, inEnd);
        }
    }
    return root;  
 }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        return buildTree(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
    }

 

Construct Binary Tree from Preorder and Inorder Traversal

标签:

原文地址:http://www.cnblogs.com/happygirl-zjj/p/4590603.html

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