zoukankan      html  css  js  c++  java
  • LeetCode "Construct Binary Tree from Preorder and Inorder Traversal"

    A collegiate textbook problem. Nothing special, but just take care of your memory use.

    class Solution {
    public:
        TreeNode *_buildTree(int pre[], int &inx_p, int np, int in[], int i0, int i1)
        {
            if(inx_p == np || i0 == i1) return NULL;
    
            TreeNode *pRoot = new TreeNode(pre[inx_p]);
            
            int inx = std::find(in + i0, in + i1, pre[inx_p++]) - in;
            
            TreeNode *pLeft = _buildTree(pre, inx_p, np, in, i0, inx);
            TreeNode *pRight = _buildTree(pre, inx_p, np, in, inx + 1, i1);
            pRoot->left = pLeft; pRoot->right = pRight;
            return pRoot;
    
        }
        TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
            int *pre = new int[preorder.size()];
            std::copy(preorder.begin(), preorder.end(), pre);
            int *in = new int[inorder.size()];
            std::copy(inorder.begin(), inorder.end(), in);
            int inx = 0;
            return _buildTree(pre, inx, preorder.size(), in, 0, inorder.size());
        }
    };
  • 相关阅读:
    相关术语随笔
    JDK简介和mac下安装和查看版本命令
    英语
    英语学习2
    英语学习-19.1
    为什么java是只有值传递而没有引用传递
    线程
    关于同步异步

    jdk动态代理实现原理总结
  • 原文地址:https://www.cnblogs.com/tonix/p/3862041.html
Copyright © 2011-2022 走看看