zoukankan      html  css  js  c++  java
  • leetcode 43:construct-binary-tree-from-inorder

    题目描述

    给出一棵树的中序遍历和后序遍历,请构造这颗二叉树
    注意:
    保证给出的树中不存在重复的节点

    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

    输入

    复制
    [2,1,3],[2,3,1]

    输出

    复制
    {1,2,3}
    



    //不需要辅助函数,简单易懂
    //后序遍历容器的最后一个数是根节点,中序遍历的根节点左边是左子树,右边是右子树,
    //后序遍历左子树节点值相邻,右子树节点值也相邻。由后序遍历最后一个值将中序遍历分成
    //左右两部分,再由这两部分的size将后序遍历分成左右两部分,递归即可
     
    class Solution {
    public:
        TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
            if(inorder.empty())
                return NULL;
            int nodeval=postorder[postorder.size()-1];
            TreeNode* head=new TreeNode(nodeval);
            vector<int>::iterator iter=find(inorder.begin(),inorder.end(),nodeval);
            vector<int>leftin=vector<int>(inorder.begin(),iter);
            vector<int>rightin=vector<int>(iter+1,inorder.end());
            int left=leftin.size();
            int right=rightin.size();
            if(left>0)
            {
                vector<int>leftpo=vector<int>(postorder.begin(),postorder.begin()+left);
                head->left=buildTree(leftin,leftpo);
            }
            if(right>0)
            {
                vector<int>rightpo=vector<int>(postorder.begin()+left,postorder.begin()+left+right);
                head->right=buildTree(rightin,rightpo);
            }
            return head;
        }
    };
  • 相关阅读:
    myeclipse中无自动提示
    ueditor使用方法
    微软开发中心的rss历史记录(10)
    微软开发中心的rss历史记录(9)
    微软开发中心的rss历史记录(6)
    微软开发中心的rss历史记录(7)
    微软开发中心的rss历史记录(8)
    P4学习:统计功能
    openCL信息汇总
    GPU/CUDA程序初体验 向量加法
  • 原文地址:https://www.cnblogs.com/hrnn/p/13416932.html
Copyright © 2011-2022 走看看