106.Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree.

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

Subscribe to see which companies asked this question

思路:后续遍历的最后一个元素就是根节点,通过这个根节点,就可以把中序遍历的元素序列划分为左右子树另个部分,确定左右左子树建立的中序遍历和后续遍历元素下标范围,可以通过这个范围递归调用函数help,继续建立左右子树,最后将左右子树和root建立连接,返回root即可。

/**
 * 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) {
        if(inorder.size()==0)//节点数目为0,直接返回NULL
            return NULL;
        return help(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
    }
    TreeNode * help(vector<int>& inorder,int start1,int end1, vector<int>& postorder,int start2,int end2){
        if(start1>end1)//下标越界,返回NULL
            return NULL;
        int val = postorder[end2];//取出根节点的值
        TreeNode * root =new TreeNode (val);//建立根节点
        int i;
        for(i=start1;i<=end1;i++)
            if(inorder[i]==val)
                break;//此处是根节点在中序遍历的位置
        int length=i-start1;//左子树元素个数
        root->left =help(inorder,start1,i-1,postorder,start2,start2+length-1);//中序遍历元素左子树下标范围[start1,i-1],后续遍历左子树元素范围[start2+length-1]
        root->right=help(inorder,i+1,end1,postorder,start2+length,end2-1);//中序遍历右子树下标范围[i+1,end1],后续遍历右子树元素范围[start2+length,end2-1]
        return root;
    }
};

 

 

 



原文地址:https://www.cnblogs.com/zhoudayang/p/5042717.html