开发者社区> 问答> 正文

一棵具有n个结点的完全二叉树以数组存储,试写一个非递归算法实现对该树的前序遍历

一棵具有n个结点的完全二叉树以数组存储,试写一个非递归算法实现对该树的前序遍历

展开
收起
知与谁同 2018-07-17 13:22:07 2469 0
3 条回答
写回答
取消 提交回答
  • 自己是前端,JS可能更熟,就用JS大概的写下
    当中可能有错误,不过总体思路是OK的
    var nodes=[];

    var top;

    for(var i =0 ; i < node;i++){

    var node =[nodes[i]]

    while(node.length){
    var one = node.pop();
    if(!top)top=one;
    console.log(one.value);
    if(one.l!==void 0){
    one.push(node);
    continue;
    }else{
    if(!one.length){
    node.push(top)
    continue;
    }
    if(one.r){
    node.push(one.r)
    }
    }
    }

    top = void 0;

    }
    2019-07-17 22:55:40
    赞同 展开评论 打赏
  • 1:问问段锡强,2:问问我。3:随便void NRPreOrder(BiTree BT,*visit(ElemType)){ if (BT) { InitStack (S); Push(S,BT); while (!StackEmpty(S)) { Pop(S,p);visit(P->data); if(p->lchild)Push (S, p->lchild); if(p->lchild)Push (S, p->lchild); } }}
    2019-07-17 22:55:40
    赞同 展开评论 打赏
  • 这个时候,玄酱是不是应该说点什么...
    #include "stdafx.h"
    #include <stack>
    #include <iostream>
    using namespace std;

    int _tmain(int argc, _TCHAR* argv[])
    {
    //构建完全二叉树,层数是三,7个节点
    int a[7] = {0,1,2,3,4,5,6};

    //前序遍历,先访问左儿子,再访问自己,再访问右儿子
    //左儿子的位置是自己游标*2+1,右儿子是自己的游标*2+2

    //队列作为缓冲
    stack<int> Temp;

    Temp.push(0);//根节点

    while(!Temp.empty())
    {
    int node = Temp.top();

    if(2*node+1 <6)//有左儿子
    {
    Temp.push(2*node+1);
    }
    else
    {
    cout<<a[node]<<endl;
    Temp.pop();

    if(Temp.empty())
    {
    getchar();
    return 0;
    }

    int parent = Temp.top();

    cout<<a[parent]<<endl;

    Temp.pop();

    Temp.push(2*parent+2);

    }
    }

    getchar();

    return 1;
    }
    2019-07-17 22:55:40
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
数据+算法定义新世界 立即下载
袋鼠云基于实时计算的反黄牛算法 立即下载
Alink:基于Apache Flink的算法平台 立即下载