Construct Binary Tree from Inorder and Postorder Traversal
来源:互联网 发布:医疗器械国家数据库 编辑:程序博客网 时间:2024/06/06 17:17
递归的思路就是通过从后向前查找postorder来获取每个子树的根节点,找到根节点后去inorder中找到对应的值,用这个值把inorder分成两半,得到左右子树的大小,用得到的左右子树的大小再去分割postorder,不断分割,构造子树
官方社区有一份代码用压栈的方式实现递归,非常简洁,思路清晰
class Solution {public: TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { if(inorder.size() == 0)return NULL; TreeNode *p; TreeNode *root; stack<TreeNode *> stn; root = new TreeNode(postorder.back()); stn.push(root); postorder.pop_back(); while(true) { if(inorder.back() == stn.top()->val) { p = stn.top(); stn.pop(); //一颗子树构造完成,把子树的根节点pop出来 inorder.pop_back(); if(inorder.size() == 0) break; if(stn.size() && inorder.back() == stn.top()->val) continue;//stn.top是子树的根节点,continue返回,构造子树 p->left = new TreeNode(postorder.back()); postorder.pop_back(); stn.push(p->left); } else { p = new TreeNode(postorder.back()); postorder.pop_back(); stn.top()->right = p; stn.push(p); //用栈实现dfs,只不过dfs是从右下位置开始的 } } return root; }};
0 0
- *(leetcode) Construct Binary Tree from Inorder and Postorder Traversal (tree)
- LeetCode[Tree]: Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode] Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- [Leetcode] Construct Binary Tree from Inorder and Postorder Traversal
- leetcode 110: Construct Binary Tree from Inorder and Postorder Traversal
- 【leetcode】Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode]Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal
- HTML5学习笔记(零)
- 添加Action 按钮
- ssh三大框架整合--jar包
- Redux系列01:从一个简单例子了解action、store、reducer
- linux多线程学习(六)——信号量实现同步
- Construct Binary Tree from Inorder and Postorder Traversal
- jvm笔记4--类文件结构
- leetcode 35. Search Insert Position
- Filter高级开发(三)——压缩响应正文内容
- GL_CLAMP GL_CLAMP_TO_EDGE GL_CLAMP_TO_BORDER
- Caffe 初学拾遗(四) CUDA 框架说明
- JSON 对象与字符串相互转换
- ural 1306 (heap推排序)
- 四川旅游总览(一)