leetcode 105: Construct Binary Tree from Preorder and Inorder Traversal
2015-08-12 15:50
495 查看
/** * Definition for a binary tree node. * 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,inorder,0,0,inorder.size()-1); } TreeNode* helper(vector<int>& preorder, vector<int>& inorder, int pre, int in_l, int in_r) { TreeNode* root=NULL; int i; for(i=in_l;i<=in_r;i++) if(inorder[i]==preorder[pre])//find the root of each subtree { root=new TreeNode(preorder[pre]); break; } if(root) { root->left=helper(preorder,inorder,pre+1,in_l,i-1); root->right=helper(preorder,inorder,pre+i-in_l+1,i+1,in_r); } return root; } };
相关文章推荐
- 360笔试--“找出第一个只出现一次的字符”
- Java出现No enclosing instance of type E is accessible. Must qualify the allocation with an enclosing
- Leetcode 188 Best Time to Buy and Sell Stock IV 至多k次买卖股票最大收益
- 关联分析(从基础到高级)
- 禁止ListView滑动
- linux学习笔记----目录处理命令----mkdir
- 1052. Linked List Sorting (25)
- Android通过post请求发送一个xml,解析返回xml数据
- 【华为机试题】最具夫妻相
- selenim java判断图片有没有加载完成
- hdu 3371 Connect the Cities(prim算法)
- python快速入门
- python 导入库问题
- hdu 3371 Connect the Cities(prim算法)
- mysql 查询字段在某个数值的临近值
- Binary Tree Level Order Traversal II
- Android UI线程和非UI线程
- solr-4.7.2目录和配置
- poj-3349 Snowflake Snow Snowflakes
- [leetcode-124]Binary Tree Maximum Path Sum(c++)