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

标签 c++ algorithm data-structures tree binary-tree

以下是将二叉搜索树的前序遍历转换为原始树的代码。

以下代码采用整数数组,表示二叉搜索树的前序遍历。返回构造树的根。

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;
}

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

我无法理解这段代码。谁能帮助我理解以下内容:

  1. 在任何给定迭代中,堆栈中存储的值与 pre[i]

  2. 指出的当前值相关
  3. 是否有任何其他迭代方法可以从给定的前序遍历构造 BST?

谢谢。

最佳答案

在构建包含 pre[i] 的节点的迭代之后,堆栈在顶部包含该节点,其下从最叶到最根的祖先和恰好一个子节点从上到下存储。

关于c++ - 从前序遍历迭代构建二叉搜索树(非递归),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22042218/

相关文章:

c++ - 当我真的不关心调用约定时,我是否应该更喜欢 "default"调用约定而不是 __fastcall?

c++ - Visual C++ 2015 表达 : _stat not working on Windows XP

c++ - 存储值 Turbo C++

algorithm - 休息时间,在 O(n^2) 中找到任何匹配毕达哥拉斯方程的三元组

algorithm - 有人可以向我解释给定头节点的双向链表的反转吗?

java 列表类型变量

c++ - 使用 C++ 在 Arduino 上编写复杂的程序。如何正确使用对象或更好地使用普通 C?

algorithm - 返回单向链表尾部(或末尾)的第 k 个元素

algorithm - 为什么我们应该使用带内存的动态规划来解决 - 最小硬币数来找零

java - 使用 ArrayList.contains() 查找匹配的值并将其从 ArrayList 中删除