前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal

LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal

作者头像
ShenduCC
发布2018-07-24 16:01:07
3370
发布2018-07-24 16:01:07
举报
文章被收录于专栏:算法修养

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

代码语言:javascript
复制
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

Return the following binary tree:

代码语言:javascript
复制
    3
   / \
  9  20
    /  \
   15   7


和105一样,稍微改一下就好了、
代码语言:javascript
复制
class Solution {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        
        vector<int> leftpost;
        vector<int> leftino;
        vector<int> rightpost;
        vector<int> rightino;
        
        if(postorder.empty()||inorder.empty())
            return NULL;
        int root = postorder[postorder.size()-1]; int left=0;int right=0;int tag=0;
        for(int i=0;i<inorder.size();i++)
        {
            if(inorder[i]==root)
            {
                tag=1;
            }
            else if(tag==0)
            {left++;leftino.push_back(inorder[i]);}
            else
            {right++;rightino.push_back(inorder[i]);}
        }
        for(int i=0;i<left;i++)
        {
            leftpost.push_back(postorder[i]);
        }
        for(int i=left;i<postorder.size()-1;i++)
        {
            rightpost.push_back(postorder[i]);
        }
        
        TreeNode* tree = new TreeNode(root);
       
        tree->left = buildTree(leftino,leftpost);
        tree->right = buildTree(rightino,rightpost);
        
        return tree;
        
        
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-06-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档