读书人

Construct Binary Tree from Inorder

发布时间: 2013-09-25 11:02:58 作者: rapoo

Construct Binary Tree from Inorder and Postorder Traversal(用中序和后序建树,在题目给定的函数中完成) 【leetcode】

题目:

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

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


中序和后序建树,做烂的都,为了符合题意,我想是尽量在题目要求的函数中完成,不借助其他函数。

第一次交超内存了,因为vector的clear其实不释放内存,坑爹。

查了一下资料,有个不错的方法可以释放内存,就是吧vector的指针强制转移成局部变量,在大括号内能自动析构。

不多说了,看代码。

/** * 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> &inorder, vector<int> &postorder) {        int len=inorder.size();        if(len==0) return NULL;        vector<int> leftin,leftpo,rightin,rightpo;        bool flag=0;        int p;        for(int i=0;i<len;++i)        {            if(inorder[i]==postorder[len-1])            {                p=i;                flag=1;            }            else if(flag==0)            {                leftin.push_back(inorder[i]);                leftpo.push_back(postorder[i]);            }            else             {                                rightin.push_back(inorder[i]);                rightpo.push_back(postorder[i-1]);            }                    }        TreeNode *root=new TreeNode(inorder[p]);        {vector<int>().swap(inorder);}        {vector<int>().swap(postorder);}        root->left=buildTree(leftin,leftpo);        root->right=buildTree(rightin,rightpo);                return root;    }};


读书人网 >操作系统

热点推荐