zoukankan      html  css  js  c++  java
  • 另一种递归构造二叉树,不同于剑指offer

    //Definition of TreeNode:
    class TreeNode {
    public:
        int val;
        TreeNode *left, *right;
        TreeNode() {
            this->val = NULL;
        }
        TreeNode(int val) {
            this->val = val;
            this->left = this->right = NULL;
        }
    };
    
    class Solution {
        /**
        *@param preorder : A list of integers that preorder traversal of a tree
        *@param inorder : A list of integers that inorder traversal of a tree
        *@return : Root of a tree
        */
    public:
        TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
            // recursive return
            TreeNode *root;
    // 迭代到没有再返回
    if (preorder.size() == 0 || inorder.size() == 0) { root = NULL; return NULL; } // write your code here int rootValue = preorder[0]; root = new TreeNode(rootValue); int index; for (int i = 0; i < inorder.size(); i++) { if (inorder[i] == rootValue) { index = i; break; } }      //黑科技构造vector,迭代器可以这么用 vector<int> lchild_preorder(preorder.begin() + 1, preorder.begin() + 1 + index); vector<int> lchild_inorder(inorder.begin(), inorder.begin() + index); int lchild_len = lchild_preorder.size(); vector<int> rchild_preorder(preorder.begin() + index + 1, preorder.end()); vector<int> rchild_inorder(inorder.begin() + index + 1, inorder.end()); int rchild_len = rchild_preorder.size(); if (root!=NULL) { //root->val = rootValue; root->left = buildTree(lchild_preorder, lchild_inorder); root->right = buildTree(rchild_preorder, rchild_inorder); } return root; } };

    http://www.lintcode.com/zh-cn/problem/construct-binary-tree-from-preorder-and-inorder-traversal/

    accepted

  • 相关阅读:
    SQL Server 触发器
    T-SQL查询进阶-10分钟理解游标
    有关T-SQL的10个好习惯
    iOS 画虚线以及drawRect的使用总结:
    iOS一个for循环实现,几行 几列 的布局形式
    IOS 符合某类型的子视图批量从父视图中移除
    DESC 和 ASC
    把数组格式数据转换成字符串存入数据库
    Swift :?和 !
    Swift 类构造器的使用
  • 原文地址:https://www.cnblogs.com/daijkstra/p/4686009.html
Copyright © 2011-2022 走看看