【一天一道LeetCode】#105. Construct Binary Tree from Preorder and Inorder Traversal

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github
欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处

(一)题目

来源:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.

(二)解题

题目大意:根据二叉树的前序和中序遍历,构造出该二叉树

剑指offer上的老题了,前序遍历的第一个节点为根节点,在中序遍历中找到该节点,其左边为根节点的左子树,后边为根节点的右子树。依次递归下去即可以重构出该二叉树。

如:123和213,前序遍历找出根节点为1,在中序遍历213中找出1,则2为左子树,3为右子树。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    typedef vector<int>::iterator vi;
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        if(preorder.empty()||inorder.empty()) return (TreeNode*)NULL;
        vi preStart = preorder.begin();
        vi preEnd = preorder.end()-1;
        vi inStart = inorder.begin();
        vi inEnd = inorder.end()-1;
        return constructTree(preStart,preEnd,inStart,inEnd);
    }
    TreeNode* constructTree(vi preStart,vi preEnd,vi inStart,vi inEnd)
    {
        //表示该节点为NULL
        if(preStart>preEnd||inStart>inEnd) return NULL;
        //前序遍历的第一个节点为根节点
        TreeNode* root = new TreeNode(*preStart);
        //只有一个节点的时候直接返回
        if(preStart==preEnd||inStart==inEnd) return root;
        vi rootIn = inStart;
        while(rootIn!=inEnd){//在中序遍历中找出根节点
            if(*rootIn==*preStart) break;
            else ++rootIn;
        }
        root->left = constructTree(preStart+1,preStart+(rootIn-inStart),inStart,rootIn-1);//递归构造左子树
        root->right = constructTree(preStart+(rootIn-inStart)+1,preEnd,rootIn+1,inEnd);//递归构造右子树
        return root;
    } 
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值