重建二叉树105. Construct Binary Tree from Preorder and Inorder Traversal
2016-11-02 17:26
453 查看
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; * 因为是**,所以采用的是递归的思想,但是由于需要标出preorder以及inorder的范围, * 所以采用下标的来标记此时下一步应该遍历的范围,但是呢,前序遍历和中序遍历由于是 * 对一个数进行遍历的,所以下一步这两个应该遍历的长度是一样的,这样的话我们可以采取迭代器 * 或者是指针来标记前序中序的起始位置,然后用一个len 来标记下一步应该涉及的范围的长度 * (建议大家先自己用手模拟一遍,然后才能更加容易的理解) */ class Solution { public: TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { return buildtree(preorder.begin(), inorder.begin(), preorder.size()); } TreeNode* buildtree(vector<int>::iterator a , vector<int>::iterator b, int len) { if (len==0) return NULL; int value = *a; // the first value of preorder TreeNode* now_root = new TreeNode (value); int mid= find(b, b+len, value) - b; // find the rank of value in the iterator b now_root->left = buildtree(a+1, b, mid); now_root->right = buildtree(a+mid+1, b+mid+1, len-mid-1); return now_root; } };
这个时间就比较尴尬了,占个坑,有时间再看看怎么写
相关文章推荐
- 剑指offer 面试题6:重建二叉树(Leetcode105. Construct Binary Tree from Preorder and Inorder Traversal) 解题报告
- <leetcode> 105. Construct Binary Tree from Preorder and Inorder Traversal 重建二叉树
- Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal 先序和中序中恢复二叉树 解题报告
- 【二叉树经典问题】105. Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode 105. 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 )根据二叉树的中序遍历和后序遍历重建二叉树
- 105\106. Construct Binary Tree from Inorder and Postorder\Preorder Traversal&重建二叉树
- [LeetCode] 105. Construct Binary Tree from Preorder and Inorder Traversal 由先序和中序遍历建立二叉树
- [LeetCode]108. Construct Binary Tree from Preorder and Inorder Traversal由前序序列和中序序列重建二叉树
- Construct Binary Tree from Preorder and Inorder Traversal 前序和中序重建二叉树
- [Leetcode] 105. Construct Binary Tree from Preorder and Inorder Traversal
- 重建二叉树106. Construct Binary Tree from Inorder and Postorder Traversal
- 105. Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode OJ:Construct Binary Tree from Preorder and Inorder Traversal(从前序以及中序遍历结果中构造二叉树)
- LeetCode-105:Construct Binary Tree from Preorder and Inorder Traversal (利用先序和中序遍历构建二叉树) -- medium
- 105. Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal
- 105. Construct Binary Tree from Preorder and Inorder Traversal
- [leetcode] 105. Construct Binary Tree from Preorder and Inorder Traversal 解题报告