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

【LeetCode】Construct Binary Tree from Preorder and Inorder Traversal

时间:2014-11-30 16:46:40      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   使用   sp   

Construct Binary Tree from Preorder and Inorder Traversal

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

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

 

可与Construct Binary Tree from Inorder and Postorder Traversal对照来看。

前序遍历Preorder的第一个节点为根,由于没有重复值,可使用根将中序Inorder划分为左右子树。

递归下去即可。

/**
 * Definition for binary tree
 * 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) {
        return Helper(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
    }
    TreeNode *Helper(vector<int> &preorder, int begin1, int end1, vector<int> &inorder, int begin2, int end2)
    {
        if(begin1 > end1)
            return NULL;
        else if(begin1 == end1)
            return new TreeNode(preorder[begin1]);
        else
        {
            //preorder[begin1] is the root
            TreeNode* root = new TreeNode(preorder[begin1]);
            int ind;
            for(ind = begin2; ind <= end2; ind ++)
            {
                if(inorder[ind] == preorder[begin1])
                    break;
            }
            //left
            root->left = Helper(preorder, begin1+1, ind-begin2+begin1, inorder, begin2, ind-1);
            //right
            root->right = Helper(preorder, end1-end2+ind+1, end1, inorder, ind+1, end2);
            return root;
        }
    }
};

bubuko.com,布布扣

 

【LeetCode】Construct Binary Tree from Preorder and Inorder Traversal

标签:style   blog   http   io   ar   color   os   使用   sp   

原文地址:http://www.cnblogs.com/ganganloveu/p/4133267.html

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