Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal

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

1. Description

Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal_第1张图片
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& inorder, vector& postorder) {
        int current = inorder.size() - 1;
        return build(postorder, inorder, current, 0, postorder.size() - 1);
    }
    
private:
    TreeNode* build(vector& postorder, vector& 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 106. Construct Binary Tree from Inorder and Postorder Traversal)