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

C++详解Leetcode:106. Construct Binary Tree from Inorder and Postorder Traversal

程序员文章站 2022-03-07 23:49:25
...

原题

C++详解Leetcode:106. Construct Binary Tree from Inorder and Postorder Traversal

思路

通过二叉树的中序遍历和后序遍历来构建二叉树,通过递归可以很简单的解决

code

/**
 * 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 l1 = 0;
        int l2 = 0;
        int r1 = inorder.size() - 1;
        int r2 = postorder.size() - 1;
        TreeNode *s = (TreeNode*)malloc(sizeof(TreeNode));
        //s = NULL;
        s = CreateBT(inorder, postorder, l1, r1, l2, r2);
        return s;
    }
    TreeNode* CreateBT(vector<int>& inorder, vector<int>& postorder, int l1, int r1, int l2, int r2)
    {
        TreeNode* s;
        int i;
        if (l1 > r1)
            return NULL;
        s = (TreeNode*)malloc(sizeof(TreeNode));
        s->left = s->right = NULL;
        for (i = l1; i <= r1; i++)
        {
            if (inorder[i] == postorder[r2])
            {
                break;
            }
        }
        s->val = inorder[i];
        s->left = CreateBT(inorder, postorder, l1, i - 1, l2, l2 + i -l1 - 1);
        s->right = CreateBT(inorder, postorder, i + 1, r1, l2 + i - l1, r2 - 1);
        return s;
    }

};
相关标签: leetcode