zoukankan      html  css  js  c++  java
  • 由中序遍历和先序遍历得出二叉树,并进行中序,先序和后序的打印

    #include <iostream>
    #include <vector>
    #include <queue>

    using namespace std;

    struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    };

    struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in)
    {
    int length = pre.size();
    if(length == 0)
    {
    return NULL;
    }

    vector<int> pre_left, pre_right, in_left, in_right;
    struct TreeNode * head = new TreeNode(pre[0]);

    int index = 0;
    for(int i = 0 ; i < length; i++)
    {
    if(pre[0] == in[i])
    {
    index = i;
    break;
    }
    }

    for(int i = 0 ; i < index; i++)
    {
    pre_left.push_back(pre[i+1]);
    in_left.push_back(in[i]);
    }
    for(int i = index+1; i < length; i++)
    {
    pre_right.push_back(pre[i]);
    in_right.push_back(in[i]);
    }

    head->left = reConstructBinaryTree(pre_left, in_left);
    head->right = reConstructBinaryTree(pre_right, in_right);

    return head;
    };

    preOrder(TreeNode * node)
    {
    if(node == NULL)
    {
    return NULL;
    }
    cout<<node->val<<" ";
    preOrder(node->left);
    preOrder(node->right);
    }
    inOrder(TreeNode * node)
    {
    if(node == NULL)
    {
    return NULL;
    }
    inOrder(node->left);
    cout<<node->val<<" ";
    inOrder(node->right);
    }


    lastOrder(TreeNode * node)
    {
    if(node == NULL)
    {
    return NULL;
    }
    lastOrder(node->left);
    lastOrder(node->right);
    cout<<node->val<<" ";
    }

    int main()
    {
    vector<int> pre = {1,2,4,7,3,5,6,8};
    vector<int> in = {4,7,2,1,5,3,8,6};

    struct TreeNode* tree = reConstructBinaryTree(pre, in);

    cout<<"Pre print: ";
    preOrder(tree);
    cout<<" in print: ";
    inOrder(tree);
    cout<<" last print: ";
    lastOrder(tree);

    return 0;
    }

  • 相关阅读:
    jsp 认知(2)
    jsp 认知
    Java 匿名类
    Usage of readonly and const
    Javascript 原型继承(续)—从函数到构造器的角色转换
    JavaScript 原型继承开端
    JS 函数调用
    Javascript Basic Operation Extraction
    JS单词形式的运算符
    git问题收集
  • 原文地址:https://www.cnblogs.com/ruigelwang/p/13155451.html
Copyright © 2011-2022 走看看