Leetcode刷题笔记 105. 从前序与中序遍历序列构造二叉树

20 篇文章 0 订阅

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
  1. 首先要了解前序和中序是怎么遍历的
    1. 前序 根节点->左子树->右子树
    2. 中序 左子树->根节点->右子树
  2. 通过观察可以发现 前序的第一个节点为根节点,我们从中序中找到这个节点就可以分成左右两个子树
  3. 假设找到的位置为index,
    1. 前序中左子树的下标范围为[preorder_start+1,preorder_start+1+index-1-inorder_start]
    2. 前序中右子树的下标范围为[preorder_end-(inorder_end-index-1),preorder_end]
    3. 中序中的左子树的下标范围为[inorder_start,index-1]
    4. 中序中右子树的下标范围为[index+1,inorder_end]
  4. 递归进行

代码

#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的一天哦!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值