Leetcode 106 根据一棵树的中序遍历与后序遍历构造二叉树

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Mr_zhuo_/article/details/88166687

根据一棵树的中序遍历与后序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]

返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7
/**
 * 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 in=0,post=0;//开始位置
        int num=inorder.size();
        return buildTree(inorder,postorder,in,post,num);
    }
    
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder,int in,int post,int num)
    {
        if(num<=0) return NULL;
        int val=postorder[post+num-1];//末尾元素为根
        int k=0;
        for(;k<num&&val!=inorder[in+k];k++);//k记录子树节点个数.注意k<num的控制条件,子树的节点数不能多于母树
        TreeNode* node=new TreeNode(val);
        node->left=buildTree(inorder,postorder,in,post,k);
        node->right=buildTree(inorder,postorder,in+k+1,post+k,num-k-1);//注意post!=post+k+1,因为根节点在尾部,所以求右子树开始位置时不必减去根节点。但是inorder中务必减去根节点
        return node;
    }
};

猜你喜欢

转载自blog.csdn.net/Mr_zhuo_/article/details/88166687