牛客剑指Offer面试题7:重建二叉树

题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

思路(递归)

1.设立一个根节点(为前序遍历第一个值)
2.在中序遍历中找到根节点,并划分了左子树和右子树(以此在前序遍历也划分开);
3.建立4个容器,分别用于后续保存前序/中序的左/右子树;
4.以根节点的索引为基础,分别在前序/中序遍历序列中都划分开左右子树,并置入相应的容器中,然后递归重复上述过程.

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        //验证有效性
        if(pre.size() <= 0 || vin.size() <= 0)
            return nullptr;
        int length = pre.size();
        //根节点
        TreeNode* root = new TreeNode(pre[0]);
        
        //分别设立先/中序遍历左子树和右子树容器
        vector<int> preLeftTree, preRightTree;
        vector<int> inLeftTree, inRightTree;
        //在中序遍历中找到根节点,并确定其索引
        int indexOfRoot_Inorder = 0;
        for(int i = 0; i < length && vin[i] != pre[0]; ++i)
            ++indexOfRoot_Inorder;
        
        //设定先序遍历序列游标
        int indexOfPreorder = 1;
        //遍历中序遍历序列划分左右子树
        for(int j = 0; j < length ; ++j)
        {
            //具体构建左子树
            if(j < indexOfRoot_Inorder)
            {
                preLeftTree.push_back(pre[indexOfPreorder]);
                indexOfPreorder++;
                inLeftTree.push_back(vin[j]);
            }
            //具体构建右子树
            else if(j > indexOfRoot_Inorder)
            {
                preRightTree.push_back(pre[indexOfPreorder]);
                indexOfPreorder++;
                inRightTree.push_back(vin[j]);
            }
        }
        
        //递归构建左子树
        root->left = reConstructBinaryTree(preLeftTree, inLeftTree);
        //递归构建右子树
        root->right = reConstructBinaryTree(preRightTree, inRightTree);
        return root;
    }
};
发布了65 篇原创文章 · 获赞 0 · 访问量 2060

猜你喜欢

转载自blog.csdn.net/ljmiiianng/article/details/103521693