zoukankan      html  css  js  c++  java
  • #Leetcode# 106. Construct Binary Tree from Inorder and Postorder Traversal

    https://leetcode.com/problems/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 helper(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);
        }
        TreeNode* helper(vector<int> &inorder, int ileft, int iright, vector<int> &postorder, int pleft, int pright) {
            if(ileft > iright || pleft > pright) return NULL;
            int i = 0;
            for(i = ileft; i < inorder.size(); ++ i)
                if(inorder[i] == postorder[pright]) break;
            TreeNode *cur = new TreeNode(postorder[pright]);
            cur -> left = helper(inorder, ileft, i - 1, postorder, pleft, pleft + i - ileft -1);
            cur -> right = helper(inorder, i + 1, iright, postorder, pleft + i - ileft, pright - 1);
            
            return cur;
        }
    };
    

      终于搞完了期末大作业剩下的就只有考试了 可爱 Be 主又每天在线10h + 激情刷题了 工作日倒数第二天 要迎接元旦假期了呢

  • 相关阅读:
    Netty
    HttpClient 该知道一些概念
    Hibernate QBC 简单收集
    IUAP--单点登录
    js图片压缩和上传并显示
    vue移动端项目
    js自定义滚动条
    mysql5.7以上版本安装
    学习webpack
    学习es6
  • 原文地址:https://www.cnblogs.com/zlrrrr/p/10190714.html
Copyright © 2011-2022 走看看