前序遍历和中序遍历树构造二叉树

根据前序遍历和中序遍历树构造二叉树.

注意事项

你可以假设树中不存在相同数值的节点

样例

给出中序遍历:[1,2,3]和前序遍历:[2,1,3]. 返回如下的树:

  2

 /  

1  3

标签

二叉树

code

/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
*@param preorder : A list of integers that preorder traversal of a tree
*@param inorder : A list of integers that inorder traversal of a tree
*@return : Root of a tree
*/
public:
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
// write your code here
TreeNode *root = NULL;
vector<int> preorder_l,preorder_r,inorder_l,inorder_r;
int i,root_index=0; if(preorder.empty()!=1 || inorder.empty()!=1) {
root = new TreeNode(preorder[0]); // 在前序队列中找根节点 // 在中序队列中找出根节点位置
for(i=0; i<inorder.size(); i++) {
if(preorder[0] == inorder[i])
break;
root_index++;
} // 左右子树的前序、中序队列
for(i=0; i<root_index; i++) {
preorder_l.push_back(preorder[i+1]);
inorder_l.push_back(inorder[i]);
}
for(i=root_index+1; i<inorder.size(); i++) {
preorder_r.push_back(preorder[i]);
inorder_r.push_back(inorder[i]);
} root->left = buildTree(preorder_l, inorder_l);
root->right = buildTree(preorder_r, inorder_r);
}
return root;
}
};

最新文章

  1. 静态工厂方法VS构造器
  2. PHP in_array效率问题
  3. 多线程编程之Windows环境下创建新线程
  4. WCF Service的Restfull风格
  5. 解决 RaspberryPi 树莓派 NTP服务异常 无法自动同步时间
  6. Centos系统备份与恢复教程
  7. IAR编译ZStack-CC2530为可下载运行的HEX文件的正确配置
  8. 嵌入式web server——Goahead移植要点
  9. Java ArrayList add(int index, E element) example
  10. 开源Math.NET基础数学类库使用(13)C#实现其他随机数生成器
  11. twisted学习笔记4 部署Twisted 应用程序
  12. Openlayer 3 最简单的弹出框
  13. React 实践项目 (五)
  14. hibernate的cascade
  15. 初识mybatis(二)
  16. centos 7 挂载U盘
  17. 创建局域网yum服务器
  18. MYSQL基本操作(下)
  19. Jenkins修改workspace和build目录
  20. Tools - 文本编辑器Notepad++

热门文章

  1. Elasticsearch 6 重要参数配置
  2. Linux常用97条命令
  3. S3C2440启动程序运行过程
  4. C语言之一般树
  5. python学习笔记:第15天 初识面向对象
  6. #include stdio.h(A)
  7. pylearn2报错缺少theano.compat.six
  8. ioc解析
  9. DocX操作word生成报表
  10. [hdu 6184 Counting Stars(三元环计数)