[Leetcode] Construct Binary Tree from Inorder and Postorder Traversal

来源:互联网 发布:高级程序员php面试 编辑:程序博客网 时间:2024/06/05 05:58

描述

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
0 0