[LeetCode]Construct Binary Tree from Preorder and Inorder Traversal
2015-12-29 15:29
399 查看
Given preorder and inorder traversal of a tree, construct the binary tree.
由树的前序遍历和中序遍历来构建子树。
首先找到根节点,然后递归找到左侧和右侧根节点完成。
由树的前序遍历和中序遍历来构建子树。
首先找到根节点,然后递归找到左侧和右侧根节点完成。
/** * 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) { int num = preorder.size(); if(num==0) return NULL; return Recursion(0, num-1, 0,preorder, inorder); } TreeNode* Recursion(int Istart,int Iend,int Pstart,vector<int>& preorder, vector<int>& inorder){ if(Istart>Iend) return NULL; TreeNode* root = new TreeNode(preorder[Pstart]); //标记根的位置,特别注意根位置的变化 int mid = 0; for(int i=Istart; i<=Iend; ++i){ if(inorder[i]==root->val) mid = i; } root->left = Recursion(Istart,mid-1,Pstart+1,preorder,inorder); //递归指向左右的根 root->right = Recursion(mid+1,Iend,Pstart+mid-Istart+1,preorder,inorder); return root; } };
相关文章推荐
- Nagios全方位接入告警-微信/电话/短信都支持
- 无网不通,有网则顺:OpenStack Neutron解析
- iOS时间与时间戳相互转换
- eclipse svn状态图标 等等都不见了。
- nginx-image模块和fastdfs module的协作
- AOP (面向切面编程)思想
- linux shell 初学 变量 循环 分支
- php.ini中开启和关闭 session auto_start 的区别
- 字符数组和字符指针
- LoadRunner脚本
- Linux下mysql5.7安装
- linux消耗CPU的shell脚本
- 设置Chrome,Firefox打开新的标签页的时候打开指定的网站
- log4cplus 编译问题
- Excel公式巧用-将新值替换旧值,新值为空保留原值
- CoUninitialize 退出时 m_pInterface->Release()崩溃 解决
- Centos7-NFS server - 笔记
- command -ubuntu
- 导航控制器切换影响UIScrollView布局
- Fragment的学习笔记