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

 

解题思路:

差不多等同于上一道,也是根据不同遍历的不同特点将树划分为更小的子树来解决。

 

代码:

/**
 * 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 build(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size()-1);
    }
private: 
    TreeNode* build(vector<int>& inorder, int il, int ir, vector<int>& postorder, int pl, int pr){
        if(il > ir || pl > pr)
            return NULL;
        int i = 0;
        for(i = il; i <= ir; i++){
            if(inorder[i] == postorder[pr]){
                break;
            }
        }
        cout<<"i = "<<i<<endl;
        TreeNode* cur = new TreeNode(inorder[i]);
        cur->right = build(inorder, i+1, ir, postorder, pr-ir+i, pr-1);
        cur->left = build(inorder, il, i-1, postorder, pl, pl+ i-1-il);
        
        return cur;
    }
};

然而57ms

让我们来看看更快的10ms解法:

class Solution {
 public:
  TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
    assert(inorder.size() == postorder.size());
    if (inorder.size() == 0) return nullptr;

    TreeNode* root;
    TreeNode** curr = &root;
    auto j = postorder.crbegin();
    stack<TreeNode*> s;
    for (auto i=inorder.crbegin(); i!=inorder.crend(); ++i) {
      while (s.empty() || s.top()->val != *i) {
        auto node = new TreeNode{*j++};
        s.push(node);
        *curr = node;
        curr = &node->right;
      }
      curr = &(s.top()->left);
      s.pop();
    }

    assert(j == postorder.crend());
    return root;
  }
};

 

posted @ 2018-06-12 10:25  妖域大都督  阅读(86)  评论(0编辑  收藏  举报