• 4、根据前序和中序,重建二叉树


    题目描述

    输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
    思路
    1、首先找到根节点
    2、确定根节点左右侧的左子树和右子树的数值
    3、找到各节点间对应的关系
    4、构建二叉树
    class Solution {
    public:
        TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) {
            int len = in.size();
            if(len == 0)
                return NULL;
            vector<int> left_pre,right_pre,left_in,right_in;
            TreeNode* head = new TreeNode(pre[0]);
            int k = 0;
            for(int i = 0;i < len;i++)
            {
                if(in[i] == pre[0])
                {
                    k = i;
                    break;
                }
            }
            for(int i = 0;i < k;i++)
            {
                left_in.push_back(in[i]);
                left_pre.push_back(pre[i+1]);
            }
            for(int i = k + 1;i < len;i++)
            {
                right_in.push_back(in[i]);
                right_pre.push_back(pre[i]);
            }
            head->left = reConstructBinaryTree(left_pre,left_in);
            head->right = reConstructBinaryTree(right_pre,right_in);
            return head;
        }
    };
  • 相关阅读:
    Mysql update case
    phpexcel导出excel等比例缩放图片
    phpexcel错误 You tried to set a sheet active by the out of bounds index: 1解决办法
    phpexcel操作
    Java io基础
    java线程基础
    java 集合基础(适用单线程)
    java 泛型深入
    Java反射基础
    Java泛型基础
  • 原文地址:https://www.cnblogs.com/zhuifeng-mayi/p/10745545.html
Copyright © 2020-2023  润新知