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.

这道题如果用递归来求解是不难的,只要根据二叉树中序和后续遍历的特点即可,不知道非递归该如何求解?

/**
 * Definition for binary tree
 * 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) {
        if (inorder.empty())
            return NULL;
        return buildTree(inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1);
    }
private:
    TreeNode *buildTree(vector<int> &inorder, int istart, int iend, 
                     vector<int> &postorder, int pstart, int pend) {
        if (istart == iend)
            return new TreeNode(inorder[istart]);
        
        int i;
        for (i=istart; i<=iend; ++i) {
            if (inorder[i]==postorder[pend]) {
                break;
            }
        }
        
        TreeNode *root = new TreeNode(inorder[i]);
        
        if (i>istart)
            root->left = buildTree(inorder, istart, i-1, postorder, pstart, pstart+i-istart-1);
        
        if (i<iend)
            root->right = buildTree(inorder, i+1, iend, postorder, pstart+i-istart, pend-1);
        
        return root;
    }
    
};


你可能感兴趣的:(递归,遍历,二叉树)