[Leetcode] 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.

给定二叉树的后序遍历以及中序遍历,要求构造该二叉树。

分析

这是一道典型的分而治之的问题。

二叉树的后序遍历的顺序是:左子数-右子树-节点,中序遍历的顺序是:左子数-节点-右子树,因此,通过后序遍历以及中序遍历,可以还原出原来的二叉树。

具体来说,后序遍历的最后一个元素表示的就是根节点,那么找到根节点之后,在中序遍历中,位于根节点左边的元素便属于左子树,位于根节点右边的元素便属于右子树,于是将问题转化成了相同的两个子问题。问题的平凡形式是某边的子树为空的情况。

相似的问题 Construct Binary Tree from Preorder and Inorder Traversal

代码

/**
 * 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) {
        return buildTree(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);
    }

    TreeNode* buildTree(vector<int>& in, int lo1, int hi1, vector<int>& post, int lo2, int hi2) {
        if (lo1 > hi1 || lo2 > hi2) return NULL;
        TreeNode* node = new TreeNode(post[hi2]);

        int i = 0;
        for(i = lo1 ;i < in.size(); i++) {
            if (in[i] == post[hi2]) break;
        }

        node->left = buildTree(in, lo1, i - 1, post, lo2, lo2 + i - lo1 - 1);
        node->right = buildTree(in, i + 1, hi1, post, hi2 - hi1 + i, hi2 - 1);

        return node;
    }
};

相关问题

Construct Binary Tree from Preorder and Inorder Traversal

这里要注意的是,给定二叉树的前序遍历以及中序遍历,或者是后序遍历以及中序遍历,都可以还原出原来的二叉树,但是如果给的是前序遍历以及后序遍历,得到的树不唯一。

这里举个简单的例子:

         1                           1
       /   \                       /   \
      2     3                     2     3
     /       \                     \   /
    4         5                     4 5
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值