73 前序遍历和中序遍历树构造二叉树

原题网址:https://www.lintcode.com/problem/construct-binary-tree-from-preorder-and-inorder-traversal/description

描述

根据前序遍历和中序遍历树构造二叉树.

你可以假设树中不存在相同数值的节点

您在真实的面试中是否遇到过这个题?  是

样例

给出中序遍历:[1,2,3]和前序遍历:[2,1,3]. 返回如下的树:

  2
 / \
1   3

标签
二叉树
 
思路:再提醒自己一遍,创建二叉树首先创建根节点,再创建并挂载左右孩子
大致思路和72题相同。
1.根节点数值为前序遍历第一个元素。
2.在中序遍历中找到根节点的索引,这样就可以确定左右子树的长度了,进一步可以确定左右子树的前序遍历和中序遍历。
3.递归创建左右子树。
4.当中序遍历起始索引大于结束索引时,二叉树建立完毕。
 
AC代码:
/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param inorder: A list of integers that inorder traversal of a tree
     * @param postorder: A list of integers that postorder traversal of a tree
     * @return: Root of a tree
     */
    TreeNode * buildTree(vector<int> &preorder, vector<int> &inorder) {
        // write your code here
    int a=inorder.size();
    int b=preorder.size();
    if (a!=b||a==0||b==0)
    {
        return NULL;
    }

    return buildtr(preorder,inorder,0,b-1,0,a-1);
    }
    
    TreeNode *buildtr(vector<int> &preorder, vector<int> &inorder,int prst,int pred,int inst,int ined)
{
    if (inst>ined)
    {
        return NULL;
    }
    int i=inst;
    while(i<=ined&&inorder[i]!=preorder[prst])
    {
        i++;
    }
    TreeNode * root=new TreeNode(preorder[prst]);
    root->left=buildtr(preorder,inorder,prst+1,prst+i-inst,inst,i-1);//左子树,递归时弄清楚索引参数;
    root->right=buildtr(preorder,inorder,prst+i-inst+1,prst+ined-inst,i+1,ined);//右子树,递归时弄清楚索引参数;
    return root;
}
    
};

 

 其他参考:
 
 

转载于:https://www.cnblogs.com/Tang-tangt/p/9273570.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值