105. 从前序与中序遍历序列构造二叉树
知识点:二叉树、递归
时间:2020年9月25日
题目链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
题目
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
示例1
输入:
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
输出:
3
/ \
9 20
/ \
15 7
解法
3
/ \
9 20
\ / \
6 15 7
前序遍历:3 9 6 20 15 7
中序遍历:9 6 3 15 20 7
后序遍历:6 9 15 7 20 3
- 首先要了解前序和中序是怎么遍历的
- 前序 根节点->左子树->右子树
- 中序 左子树->根节点->右子树
- 通过观察可以发现 前序的第一个节点为根节点,我们从中序中找到这个节点就可以分成左右两个子树
- 假设找到的位置为index,
- 前序中左子树的下标范围为[preorder_start+1,preorder_start+1+index-1-inorder_start]
- 前序中右子树的下标范围为[preorder_end-(inorder_end-index-1),preorder_end]
- 中序中的左子树的下标范围为[inorder_start,index-1]
- 中序中右子树的下标范围为[index+1,inorder_end]
- 递归进行
代码
#include <stdio.h>
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
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) {
return build(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1);
}
TreeNode* build(vector<int>& preorder, vector<int>& inorder,int preorder_start,int preorder_end,int inorder_start,int inorder_end){
if(inorder_start > inorder_end || preorder_start > preorder_end)
return nullptr;
TreeNode* root = new TreeNode(preorder[preorder_start]);
if(preorder_start == preorder_end)
return root;
int index = inorder_start;
while(inorder[index] != preorder[preorder_start])
index++;
root->left = build(preorder, inorder,preorder_start+1,preorder_start+1+index-1-inorder_start,inorder_start,index-1);
root->right =build(preorder, inorder,preorder_end-(inorder_end-index-1),preorder_end,index+1,inorder_end);
return root;
}
};
void printTree(TreeNode* root){
if(root==nullptr){return;}
printTree(root->left);
printTree(root->right);
cout<<root->val<<endl;
}
int main()
{
vector<int> inorder {9,6,3,15,20,7};
vector<int> postorder{6,9,15,7,20,3};
Solution s;
TreeNode *root = s.buildTree(inorder, postorder);
printTree(root);
return 0;
}
今天也是爱zz的一天哦!