📌  相关文章
📜  从给定的前序遍历构造BST |设置 3(朴素方法)

📅  最后修改于: 2021-09-03 14:36:05             🧑  作者: Mango

给定二叉搜索树的先序遍历,构造 BST。
例如,如果给定的遍历是 {10, 5, 1, 7, 40, 50},那么输出应该是后续树的根。

10
   /   \
  5     40
 /  \      \
1    7      50

我们在之前的文章中讨论了构造二叉搜索树的方法。这里是另一种在给定前序遍历时构造二叉搜索树的方法。

我们知道 BST 的中序遍历以非递减的方式给出元素。因此我们可以对给定的前序遍历进行排序以获得二叉搜索树的中序遍历。

我们已经在这篇文章中学习了在给定前序和中序遍历时构造树的方法。我们现在将使用相同的方法来构建 BST。

CPP
#include
using namespace std;
 
// A BST node has data, pointer to left
// child and pointer to right child
struct Node {
    int data;
    Node *left, *right;
};
 
// A utility function to create new node
Node* getNode(int data)
{
    Node* temp = new Node();
    temp->data = data;
    temp->left = temp->right = NULL;
 
    return temp;
}
 
/* Recursive function to construct BST
Inorder traversal in[] and Preorder traversal
pre[]. Initial values of inStart and inEnd should be
0 and n -1.*/
Node* buildBTRec(int in[], int pre[], int inStart,
            int inEnd, unordered_map& m)
{
    static int preIdx = 0;
    if (inStart > inEnd)
        return NULL;
 
    // Pick current node from Preorder traversal
    // using preIndex and increment preIndex
    int curr = pre[preIdx];
    ++preIdx;
 
    Node* temp = getNode(curr);
 
    // If this node has no children then return
    if (inStart == inEnd)
        return temp;
 
    // Else find the index of this node in
    // inorder traversal
    int idx = m[curr];
 
    // Using this index construct left and right subtrees
    temp->left = buildBTRec(in, pre, inStart, idx - 1, m);
    temp->right = buildBTRec(in, pre, idx + 1, inEnd, m);
 
    return temp;
}
 
// This function mainly creates a map to store
// the indices of all items so we can quickly
// access them later.
Node* buildBST(int pre[], int n)
{
    // Copy pre[] to in[] and sort it
    int in[n];
    for (int i = 0; i < n; i++)
        in[i] = pre[i];
    sort(in, in + n);
 
    unordered_map m;
    for (int i = 0; i left);
    cout 


Python3
# A BST node has data, pointer to left
# child and pointer to right child
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None
 
# /* Recursive function to construct BST
# Inorder traversal in[] and Preorder traversal
# pre[]. Initial values of inStart and inEnd should be
# 0 and n -1.*/
def buildBTRec(inn, pre, inStart, inEnd):
    global m, preIdx
 
    if (inStart > inEnd):
        return None
 
    # Pick current node from Preorder traversal
    # using preIndex and increment preIndex
    curr = pre[preIdx]
    preIdx += 1
 
    temp = Node(curr)
 
    # If this node has no children then return
    if (inStart == inEnd):
        return temp
 
    # Else find the index of this node in
    # inorder traversal
    idx = m[curr]
 
    # Using this index construct left and right subtrees
    temp.left = buildBTRec(inn, pre, inStart, idx - 1)
    temp.right = buildBTRec(inn, pre, idx + 1, inEnd)
 
    return temp
 
# This function mainly creates a map to store
# the indices of all items so we can quickly
# access them later.
def buildBST(pre, n):
    global m
     
    # Copy pre[] to in[] and sort it
    inn=[0 for i in range(n)]
 
    for i in range(n):
        inn[i] = pre[i]
 
    inn = sorted(inn)
 
    for i in range(n):
        m[inn[i]] = i
 
    return buildBTRec(inn, pre, 0, n - 1)
 
def inorderTraversal(root):
    if (root == None):
        return
    inorderTraversal(root.left)
    print(root.data, end = " ")
    inorderTraversal(root.right)
 
# Driver Program
if __name__ == '__main__':
    m,preIdx = {}, 0
    pre = [100, 20, 10, 30, 200, 150, 300]
    n = len(pre)
 
    root = buildBST(pre, n)
 
    # Let's test the built tree by printing its
    # Inorder traversal
    print("Inorder traversal of the tree is")
    inorderTraversal(root)
 
# This code is contributed by mohit kumar 29


输出:
Inorder traversal of the tree is 
10 20 30 100 150 200 300

时间复杂度:排序需要 O(nlogn) 时间,使用预序和中序遍历进行排序和构造需要线性时间。因此,上述解决方案的总时间复杂度为 O(nlogn)。

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live