zoukankan      html  css  js  c++  java
  • PTA 7-23 还原二叉树

    知识点:

    • 根据前序遍历和中序遍历还原二叉树

    给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。

    根据二叉树的性质,如果我们只给出二叉树的一种遍历方式的结果,不能完全确定一颗二叉树,这时的二叉树可能具有多种形态。但是当我们给出一颗二叉树的两种不同遍历方式的时候,就可以完全确定一颗二叉树。

    这里以前序遍历和中序遍历为例。
    假如我们给出两棵二叉树的前中序遍历分别为

    前序遍历:ABDFGHIEC
    中序遍历:FDHGIBEAC

    • 由前序遍历的性质,我们可以知道 A 一定是这棵树的根结点
    • 根据中序遍历可知, A 左边的一定是 A 的左子树,A 右边的一定是 A 的右子树
    • 同理,B 为 A 的左子树的根结点……
    • 如此递归下去就可以生成一颗确定的二叉树

    由此,我们就可以写出递归的还原二叉树的代码:

    #include <iostream>
    #include <string>
    using namespace std;
    
    struct node {
        char data;
        node *left, *right;
        node(char _data): data(_data), left(NULL), right(NULL) {}
    };
    
    int n;  // 总结点数目
    string preOrder, inOrder;
    
    node *createTree(int preL, int preR, int inL, int inR) {
        if(preL > preR)
            return NULL;
        char nowChar = preOrder[preL];
        node *root = new node(nowChar);
        int pos = inOrder.find(nowChar);
        int len = pos - inL;    // 左子树的长度
        root->left = createTree(preL + 1, preL + len, inL, pos - 1);
        root->right = createTree(preL + len + 1, preR, pos + 1, inR);
        return root;
    }
    
    int getHeight(node *root) {
        if(root == NULL)
            return 0;
        else
            return max(getHeight(root->left), getHeight(root->right)) + 1;
    }
    
    int main()
    {
        cin >> n >> preOrder >> inOrder;
        node *root = createTree(0, preOrder.size()-1, 0, inOrder.size() - 1);
        printf("%d", getHeight(root));
        return 0;
    }
    
  • 相关阅读:
    nginx能访问html静态文件但无法访问php文件
    LeetCode "498. Diagonal Traverse"
    LeetCode "Teemo Attacking"
    LeetCode "501. Find Mode in Binary Search Tree"
    LeetCode "483. Smallest Good Base" !!
    LeetCode "467. Unique Substrings in Wraparound String" !!
    LeetCode "437. Path Sum III"
    LeetCode "454. 4Sum II"
    LeetCode "445. Add Two Numbers II"
    LeetCode "486. Predict the Winner" !!
  • 原文地址:https://www.cnblogs.com/veeupup/p/12631534.html
Copyright © 2011-2022 走看看