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

    Title:

    Given preorder and inorder traversal of a tree, construct the binary tree.

    使用递归构建。

    /**
     * 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:
        TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
            return maker(preorder.begin(),preorder.end(),inorder.begin(),inorder.end());
        }
        template <typename Iter>
        TreeNode* maker(Iter pFirst,Iter pLast,Iter qFirst,Iter qLast){
            if (pFirst == pLast)
                return NULL;
            TreeNode *root = new TreeNode(*pFirst);
            Iter i = find(qFirst,qLast,*pFirst);
            int leftSize = distance(qFirst,i);
            root->left = maker(pFirst+1,pFirst+leftSize+1,qFirst,qFirst+leftSize);
            root->right = maker(pFirst+leftSize+1,pLast,qFirst+leftSize+1, qLast);
            return root;
        }
    };

    Title:

    Given inorder and postorder traversal of a tree, construct the binary tree.

    /**
     * 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:
        TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
            return maker(inorder.begin(),inorder.end(),postorder.begin(),postorder.end());
        }
        
        template <typename Iter>
        TreeNode* maker(Iter pFirst,Iter pLast,Iter qFirst, Iter qLast){
            if (pFirst == pLast)
                return NULL;
            
            Iter iter = find(pFirst,pLast,*(qLast-1));
            int size = distance(pFirst,iter);
            TreeNode* root = new TreeNode(*(qLast-1));
            root->left = maker(pFirst,pFirst+size,qFirst,qFirst+size);
            root->right = maker(pFirst+size+1,pLast,qFirst+size,qLast-1);
            return root;
        }
    };
  • 相关阅读:
    php操作redis cluster集群成功实例
    js算法-快速排序(Quicksort)
    如何编写自己的虚拟DOM
    一文带你看透kubernetes 容器编排系统
    SpringBoot AOP控制Redis自动缓存和更新
    机器学习中的numpy库
    时间戳转自定义日期格式和刚刚、十分钟前等友好日期格式
    Python数据处理实例
    Spark1.x和2.x如何读取和写入csv文件
    掌握这个Python小技巧,轻松构建cytoscape导入文件
  • 原文地址:https://www.cnblogs.com/yxzfscg/p/4500844.html
Copyright © 2011-2022 走看看