刷题-力扣-106. 从中序与后序遍历序列构造二叉树

106. 从中序与后序遍历序列构造二叉树

题目链接

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/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. 根据后序序列找到父节点,再根据父节点在中序序列中找出该父节点的左右子树
  3. 按照步骤2级进行递归构造结点

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        int inorderLen = inorder.size();
        int postorderLen = postorder.size();
        if (inorderLen == 0 || postorderLen == 0) return nullptr;
        return recursion(inorder, 0, inorderLen - 1, postorder, 0, postorderLen - 1);
    }

private:
    TreeNode* recursion(vector<int>& inorder, int inorderLeft, int inorderRight, vector<int>& postorder, int postorderLeft, int postorderRight) {
        if (inorderLeft > inorderRight || postorderLeft > postorderRight) return nullptr;
        TreeNode* node = new TreeNode(postorder[postorderRight]);
        int mid;
        for (mid = inorderLeft; mid < inorderRight; ++ mid) {
            if (inorder[mid] == postorder[postorderRight]) break;
        }
        node->left = recursion(inorder, inorderLeft, mid - 1, postorder, postorderLeft, postorderLeft + mid - inorderLeft - 1);
        node->right = recursion(inorder, mid + 1, inorderRight, postorder, postorderLeft + mid - inorderLeft, postorderRight - 1);
        return node;
    }

};
上一篇:【ZooKeeper Notes 4】可视化zookeeper的事务日志


下一篇:git与pycharm的使用详解(git+gitlab+pycham)