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

    说明:

           1)实现与根据先序和中序遍历构造二叉树相似,题目参考请进

    算法思想

    中序序列:C、B、E、D、F、A、H、G、J、I
     
    后序序列:C、E、F、D、B、H、J、I、G、A
     
    递归思路:
    1. 根据后序遍历的特点,知道后序遍历最后一个节点为根节点,即为A
    2. 观察中序遍历,A左侧CBEDF为A左子树节点,A后侧HGJI为A右子树节点
    3. 然后递归的构建A的左子树和后子树

    实现:

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
    13         return creatTree(inorder.begin(),inorder.end(),postorder.begin(),postorder.end());
    14     }
    15 private:
    16     template<typename InputIterator>
    17     TreeNode *creatTree(InputIterator in_beg,InputIterator in_end,InputIterator post_beg,InputIterator post_end)
    18     {
    19         if(in_beg==in_end||post_beg==post_end) return nullptr; //空树
    20         TreeNode *root=new TreeNode(*(post_end-1));
    21         auto inRootPos=find(in_beg,in_end,root->val);//中序遍历中找到根节点,返回迭代指针
    22         int leftlen=distance(in_beg,inRootPos);//中序遍历起点指针与找到的根节点指针的距离
    23         root->left=creatTree(in_beg,inRootPos,post_beg,next(post_beg,leftlen));//递归构建左子数
    24         root->right=creatTree(next(inRootPos),in_end,next(post_beg,leftlen),post_end-1);//递归构建右子树
    25         return root;
    26     }
    27 };
  • 相关阅读:
    红黑树——面试相关
    汇编常用指令
    c++11 delete禁用函数
    【转】C++可变参数列表处理宏va_list、va_start、va_end的使用
    【转】C/C++函数调用过程分析
    引用的大小
    多线程面试
    2017.08.22网易面试问题记录
    c++ 重载->
    探究Java如何实现原子操作(atomic operation)
  • 原文地址:https://www.cnblogs.com/zhoutaotao/p/3833324.html
Copyright © 2011-2022 走看看