zoukankan      html  css  js  c++  java
  • 给出树的前序遍历和后序遍历,构建树

    必须知道一点:

    前序遍历是:根、左、右

    中序遍历是:左、根、右

    后序遍历是:左、右、根

    递归构建即可。

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) {
            if(pre.size()==0)return NULL;
            TreeNode *root=new TreeNode(pre[0]);
            int p=0;
            while(in[p]!=(root->val))p++;
            root->left = reConstructBinaryTree(vector<int>(pre.begin()+1, pre.begin() + p+ 1),  vector<int>(in.begin(),in.begin() + p));
            root->right = reConstructBinaryTree(vector<int>(pre.begin() + p+ 1, pre.end() ) , vector<int>(in.begin() + p + 1, in.end() ));
            return root;
        }
    };
  • 相关阅读:
    46 Simple Python Exercises-Higher order functions and list comprehensions
    IDEA一些设置
    DDD建模案例----“视频课程”场景
    LA 4727
    uva 1377
    uva 1421
    UVA
    LA 4731
    uva 11404
    uva 11143
  • 原文地址:https://www.cnblogs.com/pk28/p/5817353.html
Copyright © 2011-2022 走看看