zoukankan      html  css  js  c++  java
  • [LeetCode]109. 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.

    解法:这题和由前序序列和中序序列重建二叉树一样,解法也相同,不过是先根据后序序列的最后一个元素为树根,再将中序序列划分为左右子树来递归完成。注意确定左右子树时中序序列和后序序列的两个下标值。rootIndex只能确定中序序列中左右子树的元素,而不能确定后序序列的左右子树元素位置,后者需要根据左右子树元素个数来确定:从第一个开始的leftLength个为左子树元素,接下来的rightLength个为右子树元素,最后一个为树根。

    /**
     * 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) {
            int in = inorder.size(), pn = postorder.size();
            if (in == 0 || pn == 0 || in != pn) return NULL;
            return buildRecursion(inorder, 0, in - 1, postorder, 0, pn - 1);
        }
    private:
        TreeNode* buildRecursion(vector<int>& inorder, int ibeg, int iend, vector<int>& postorder, int pbeg, int pend) {
            TreeNode *root = new TreeNode(postorder[pend]);
            if (ibeg == iend) return root;
            int rootIndex = ibeg;
            while (rootIndex <= iend && inorder[rootIndex] != root->val) 
                ++rootIndex;
            int leftLength = rootIndex - ibeg, rightLength = iend - rootIndex;
            if (leftLength > 0) 
                root->left = buildRecursion(inorder, ibeg, rootIndex - 1, postorder, pbeg, pbeg + leftLength - 1);
            if (rightLength > 0) 
                root->right = buildRecursion(inorder, rootIndex + 1, iend, postorder, pend - rightLength, pend - 1);
            return root;
        }
    };
  • 相关阅读:
    opencart后台操作--第一节 多语言篇---中文语言包
    Apache mod_rewrite实现HTTP和HTTPS重定向跳转
    js搞定网页的简繁转换
    TP5 首页导航一级和二级分类
    php中is_null,empty,isset,unset 的区别详细介绍
    thinkPHP5 引入模板
    mac Gitblit安装
    springCloud 之 Eureka注册中心高可用配置
    spring cloud config-配置中心
    链路追踪工具Zipkin简单整合
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/5046162.html
Copyright © 2011-2022 走看看