DFS Construct Binary Tree from Preorder and Inorder Traversal
来源:互联网 发布:adobe cc2018 mac破解 编辑:程序博客网 时间:2024/04/26 01:50
思路:
DFS。
Example:
Pre-Order:4 2 1 3 5 6
In-Order:1 2 3 4 5 6
先从Pre-Order中找到的第一个肯定是root,这里是4,然后从In-Order中以4为界,左边是root的左子树的元素,右边是root的右子树的元素,这里1,2,3是root的左子树的元素,5,6是root的右子树的元素,依次类推,再构造root的左子树和右子树,并且让root->left = 构造的左子树rootLeft & root->right = 构造的右子树的rootRight 。
/** * 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 {private: //Construct Binary Tree from Preorder and Inorder Traversal template<typename Iter> TreeNode* build(Iter pBegin, Iter pEnd, Iter iBegin, Iter iEnd) { if(pBegin == pEnd) return NULL; if(iBegin == iEnd) return NULL; int val = *pBegin; auto iRoot = find(iBegin, iEnd, val); TreeNode *root = new TreeNode(*iRoot); int leftSize = iRoot - iBegin; root->left = build(pBegin+1, pBegin+leftSize+1, iBegin, iRoot); root->right = build(pBegin+leftSize+1, pEnd, iRoot+1, iEnd); return root; }public: TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { size_t size = inorder.size(); if(size == 0) return NULL; return build(preorder.begin(), preorder.end(), inorder.begin(), inorder.end()); }};
0 0
- Leetcode dfs Construct Binary Tree from Preorder and Inorder Traversal
- DFS Construct Binary Tree from Preorder and Inorder Traversal
- *(leetcode) Construct Binary Tree from Preorder and Inorder Traversal (tree)
- LeetCode[Tree]: Construct Binary Tree from Preorder and Inorder Traversal
- [leetcode][tree] Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal & Construct Binary Tree from Inorder and P
- LeetCode: Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode]Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode Construct Binary Tree from Preorder and Inorder Traversal
- [Leetcode] Construct Binary Tree from Preorder and Inorder Traversal
- Leetcode: Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode Construct Binary Tree from Preorder and Inorder Traversal
- leetcode 109: Construct Binary Tree from Preorder and Inorder Traversal
- 【leetcode】Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- 自定义实现String类
- android中实现求昨天的日期的代码工具类
- NSNumber
- java内部类的基本理解
- android自定义view粒子效果之雨-续
- DFS Construct Binary Tree from Preorder and Inorder Traversal
- 单点登录(SSO)服务
- Spring MVC之@RequestParam @RequestBody @RequestHeader 等详解
- Spring MVC基础
- 《剑指Offer》学习笔记--面试题43:n个骰子的点数
- org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current 出错
- MySQL命令大全
- 三只小猫枕边生活 三只小猫枕边生活 这个美女泛滥成灾的国度,急需要男
- vim 配置