LeetCode--construct binary tree from inorder and postorder-traversal(根据中序和后序遍历重建二叉树)C++

题目描述:Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

思路分析:本题要求我们通过二叉树的中序和后序遍历还原这个二叉树,我们知道二叉树的中序遍历的顺序是:左子树–>根节点–>右子树,后序遍历的 顺序是:左子树–>右子树–>根节点。
我们可以借助递归思想,根据后序的顺序的最后一个节点为树的根节点,将中序遍历分为两部分,根的左子树,根的右子树。

代码实现:

/**
 * Definition for binary tree
 * 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) 
    {
        return buildTree_t(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
    }

    TreeNode *buildTree_t(vector<int> &inorder,int iLeft,int iRight, vector<int> &postorder,int pLeft,int pRight)
    {
        if(iLeft > iRight || pLeft > pRight)
            return NULL;

        TreeNode* cur = new TreeNode(postorder[pRight]);
        int i=0;
        for(i=iLeft;iif(inorder[i] == cur->val)
                break;
        }
        cur->left=buildTree_t(inorder,iLeft,i-1,postorder,pLeft,pLeft+i-iLeft-1);
        cur->right=buildTree_t(inorder,i+1,iRight,postorder,pLeft+i-iLeft,pRight-1);
        return cur;
    }
};

你可能感兴趣的:(数据结构与算法,C++,每日一题)