首页 > 代码库 > 根据中序遍历和后序遍历树构造二叉树

根据中序遍历和后序遍历树构造二叉树

根据中序遍历和后序遍历树构造二叉树

样例:

给出树的中序遍历: [1,2,3] 和后序遍历: [1,3,2]

返回如下的树:

  2

 /  \

1   3

借鉴上一篇《前序遍历和中序遍历树构造二叉树》,我们知道中序遍历为左->中->右,后序遍历为左->右->中。于是后序遍历的最后一个值即为根节点的值,根据这个值我们在中序遍历中找到根节点左子树和右子树的值,递归构造左子树和右子树即可。

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
 

class Solution {
    /**
     *@param inorder : A list of integers that inorder traversal of a tree
     *@param postorder : A list of integers that postorder traversal of a tree
     *@return : Root of a tree
     */
public:

    TreeNode *construct(vector<int> &inorder, vector<int> &postorder, 
        int is, int ie, int ps, int pe) {
            TreeNode * root = new TreeNode(postorder[pe]);
            if (ps == pe) return root;
            int i;
            for (i = 0; i < ie; i++) {
                if (inorder[i] == root->val) break;
            }
            if (i-1 >= is) {
                root->left = construct(inorder, postorder, is, i-1, ps, ps+i-1-is);
            }
            if (i+1 <= ie) {
                root->right = construct(inorder, postorder, i+1, ie, ps+i-is, pe-1);
            }
            return root;            
        }


    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        if (inorder.empty() || postorder.empty() || 
            inorder.size() != postorder.size()) return NULL;
        return construct(inorder, postorder, 0, inorder.size()-1, 0, postorder.size()-1);
    }
};

 

根据中序遍历和后序遍历树构造二叉树