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

LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal

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

Given preorder and inorder traversal of a tree, construct the binary tree.

Note: You may assume that duplicates do not exist in the tree.

For example, given

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

Return the following binary tree:

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


已知二叉树的前序遍历这中序遍历,求二叉树,这个其实挺简单的,在前序遍历中取第一个元素,然后在中序遍历找到相应的元素,左边的为左子树,右边的为右子树,根据长度在前序遍历中找到相应左子树和右子树的前序遍历。然后就可以递归了。
代码语言:javascript
复制
class Solution {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        
        vector<int> leftpre;
        vector<int> leftino;
        vector<int> rightpre;
        vector<int> rightino;
        
        if(preorder.empty()||inorder.empty())
            return NULL;
        int root = preorder[0]; 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=1;i<left+1;i++)
        {
            leftpre.push_back(preorder[i]);
        }
        for(int i=left+1;i<preorder.size();i++)
        {
            rightpre.push_back(preorder[i]);
        }
        
        TreeNode* tree = new TreeNode(root);
       
        tree->left = buildTree(leftpre,leftino);
        tree->right = buildTree(rightpre,rightino);
        
        return tree;
        
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-06-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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