简体   繁体   English

从前序遍历迭代(非递归)构建二叉搜索树

[英]Construction of Binary Search Tree from preorder traversal iteratively (not recursion)

The following is the code to converted a preorder traversal of a Binary Search Tree to the original tree.以下是将二叉搜索树的前序遍历转换为原始树的代码。

The following code takes an array of integers, which represent the pre order traversal of aa Binary search tree.下面的代码采用一个整数数组,它表示二叉搜索树的前序遍历。 The root of the construct tree is returned.返回构造树的根。

struct Node* constructTree(int pre[], int size)
{
    stack<struct Node* > s;
    int i;
    struct Node* root=newNode(pre[0]);
    struct Node* temp;
    struct Node* top_node;
    s.push(root);
    for(i=1;i<size;i++)
    {
        temp=NULL;
        while(!s.empty()&&pre[i]>(s.top()->data))
            {
                temp=s.top();
                s.pop();
            }
            if(temp==NULL)
            {
                top_node=s.top();
                top_node->left=newNode(pre[i]);
                s.push(top_node->left);
            }else
            {
                temp->right=newNode(pre[i]);
                s.push(temp->right);
            }
    }


    return root;
}

Source: http://www.geeksforgeeks.org/construct-bst-from-given-preorder-traversal-set-2/资料来源: http : //www.geeksforgeeks.org/construct-bst-from-given-preorder-traversal-set-2/

I have trouble understanding this code.我无法理解此代码。 Can anybody help me understand the following:任何人都可以帮助我理解以下内容:

  1. At any given iteration, what values are stored in the stack, in relation to the current value being pointed out by pre[i]在任何给定的迭代中,相对于pre[i]指出的当前值,堆栈中存储了哪些值

  2. Is there any other iterative method for constructing a BST from a given preorder traversal?有没有其他迭代方法可以从给定的前序遍历构造 BST?

Thank you.谢谢你。

在构造包含pre[i]的节点的迭代之后,堆栈包含顶部的节点,在该节点下,它的最叶到最根的祖先只具有一个孩子,从上到下存储。

Check if this works:检查这是否有效:

public:
TreeNode* bstFromPreorder(vector<int>& preorder) {
    TreeNode *root = new TreeNode(preorder[0]);
    stack<TreeNode*> nodes;
    nodes.push(root);
    for (int i = 1; i < preorder.size(); i++) {
        TreeNode *temp = new TreeNode(preorder[i]);
        if (temp->val < nodes.top()->val)
            nodes.top()->left = temp;
        else {
            TreeNode *prev;
            while (!nodes.empty() && nodes.top()->val < temp->val) {
                prev = nodes.top();
                nodes.pop();
            }
            prev->right = temp;
        }
        nodes.push(temp);
    }
    return root;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM