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

For example, given

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

题目给出二叉数的中序和后序遍历,要求写出二叉树的具体形式。
后序遍历的遍历数序为左子树->右子树->根结点,因此最后一个结点就是二叉树的根结点,
由根结点可将中序遍历分成左子树和右子树,再根据左子树的结点数,将后序遍历中的左子树和右子树分开。
再对左子树和右子树进行相同的操作。

代码如下:
class Solution {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        return build(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
    }
    TreeNode* build(vector<int>& inorder,int iLeft,int iRight, vector<int>& postorder,int pLeft,int pRight){
        if(iLeft>iRight || pLeft>pRight)return NULL;
        
        TreeNode* root=new TreeNode(postorder[pRight]);;
        int i=iLeft;
        while(i<=iRight){
            if(inorder[i]==postorder[pRight]){
                break;
            }
            ++i;
        }
        
        root->left=build(inorder,iLeft,i-1,postorder,pLeft,pLeft+i-iLeft-1);
        root->right=build(inorder,i+1,iRight,postorder,pLeft+i-iLeft,pRight-1);
        
        return root;
    }
};

i-iLeft计算出左子树的结点数。

posted @ 2019-06-03 18:21  程嘿嘿  阅读(94)  评论(0编辑  收藏  举报