zoukankan      html  css  js  c++  java
  • 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;
      }
    };
  • 相关阅读:
    DB2—alter追加/删除/重置column操作
    piwik网站访问统计系统
    二、ELKStack集群架构设计
    vnstat 查看服务器带宽统计命令
    JavaScript实现瀑布流
    ansible安装文档
    tornado框架介绍
    运维工程师主要工作是做什么?
    vmware workstation无法打开内核设备问题处理办法
    Python开发之AJAX全套
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9171845.html
Copyright © 2011-2022 走看看