【leetocde】 105. Construct Binary Tree from Preorder and Inorder Traversal
2016-06-25 21:39
555 查看
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
Subscribe to see which companies asked this question
递归就可以了。
Note:
You may assume that duplicates do not exist in the tree.
Subscribe to see which companies asked this question
递归就可以了。
#include<algorithm> using namespace std; /** * 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) { if(preorder.size()==0||inorder.size()==0||find(inorder.begin(),inorder.end(),preorder[0])==inorder.end()) return NULL; auto rootindex=find(inorder.begin(),inorder.end(),preorder[0]); TreeNode *root = new TreeNode(preorder[0]); vector<int> subleft,subright; preorder.erase(preorder.begin()); if(rootindex!=inorder.begin()) subleft.insert(subleft.begin(),inorder.begin(),rootindex); if(rootindex!=inorder.end()-1) subright.insert(subright.begin(),rootindex+1,inorder.end()); root->left=buildTree(preorder,subleft); root->right=buildTree(preorder,subright); return root; } };
相关文章推荐
- linux系统设置静态IP 查看网卡配置文件
- CentOS 7 网络配置
- JS中substr和substring的用法和区别
- 一些资源分享
- Javascript学习笔记——正则表达式
- springmvc——入门学习
- 【Remoting】.Net remoting方法实现简单的在线升级(上篇:更新文件)
- geotrellis使用(十一)实现空间数据库栅格化以及根据属性字段进行赋值
- jquery $("#id") 和document.getElementById("id")的区别
- ContentProvider内容提供商的简单使用(下)
- 51nod 1417 天堂里的游戏
- 【Java】JavaEE 13 规范
- python代码风格规范
- android 四大组件之Service(10) AIDL android interface definition language
- 时间复杂度和空间复杂度
- C语言学习(一)
- 实习Week 0
- 数据结构之图的实现
- ffmpeg播放声音(三)
- Java开发中的23种设计模式详解