• LeetCode 106. 从中序与后序遍历序列构造二叉树(Construct Binary Tree from Inorder and Postorder Traversal)


    题目描述

    根据一棵树的中序遍历与后序遍历构造二叉树。

    注意:
    你可以假设树中没有重复的元素。

    例如,给出

    中序遍历 inorder = [9,3,15,20,7]
    后序遍历 postorder = [9,15,7,20,3]

    返回如下的二叉树:

        3
       / 
      9  20
        /  
       15   7

    解题思路

    利用回溯的思想,分别记录生成树时中序遍历和后序遍历对应的段首、段尾,每次构造树时首先构造根节点为后序遍历的尾节点,接着在中序遍历序列中找到根的位置,然后根左对应左子树,根右对应右子树,对应到后序遍历序列中分隔成两段,递归构造左子树和右子树。

    代码

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
    13         return build(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1);
    14     }
    15     TreeNode* build(vector<int> inorder, vector<int> postorder, int iLeft, int iRight, int pLeft, int pRight){
    16         if(pLeft > pRight) return NULL;
    17         TreeNode* root = new TreeNode(postorder[pRight]);
    18         int idx = iLeft;
    19         while(inorder[idx] != postorder[pRight]) idx++;
    20         root->left = build(inorder, postorder, iLeft, idx - 1, pLeft, pLeft + idx - iLeft - 1);
    21         root->right = build(inorder, postorder, idx + 1, iRight, pLeft + idx - iLeft, pRight - 1);
    22         return root;
    23     }
    24 };
  • 相关阅读:
    Java九种基本数据类型的大小,以及他们的封装类
    php之正则表达式
    代码开发注意事项
    提后端需求的要求
    后端上线规范
    关注公众号的微信用户收到非本人操作的充值消费记录,故障记录
    软件三层架构和MVC模式的区别
    HttpClient发送请求和接收参数
    js页面倒计时
    小程序换取openId
  • 原文地址:https://www.cnblogs.com/wmx24/p/9510338.html
Copyright © 2020-2023  润新知