欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal

程序员文章站 2022-03-04 19:05:04
...

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal

2. Solution

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

private:
    TreeNode* build(vector<int>& postorder, vector<int>& inorder, int& current, int start, int end) {
        if(current == -1 || start > end) {
            return nullptr;
        }
        int value = postorder[current];
        TreeNode* node = new TreeNode(value);
        int index = 0;
        for(int i = start; i <= end; i++) {
            if(inorder[i] == value) {
                index = i;
                break;
            }
        }
        current--;
        node->right = build(postorder, inorder, current, index + 1, end);
        node->left = build(postorder, inorder, current, start, index - 1);
        return node;
    }
};

Reference

  1. https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/
相关标签: Leetcode