博客
关于我
二叉树之先序遍历
阅读量:424 次
发布时间:2019-03-06

本文共 1120 字,大约阅读时间需要 3 分钟。

  二叉树不同于列表、链表、栈、队列这些线性结构,也不同于图这种非线性结构,它属于半线性结构。我们在搞二叉树的时候不要从轮子造起,而要善于引用此前的工作成果,转化成以前已经玩烂的线性结构。

  根据树根、左娃、右娃的先后顺序,分别有先序遍历(V-L-R)、中序遍历(L-V-R)、后序遍历(L-R-V),说一个先序遍历就够了。

  先序遍历的递归实现方法:

template 
void traverse(BinNodePosi(T) x,VST & visit){ if(!x) return; visit(x->data); traverse(x->lChild,visit); traverse(x->rChild,visit); }

  先序遍历的迭代实现方法(栈)一:

template 
void traverse(BinNodePosi(T) x,VST & visit){ stack
S; //辅助栈 if(x) S.push(x); //根节点入栈 while( !S.empty()){ x=S.pop(); visit(x->data); if( hasRchild(x) ) S.push( x->rChild ); if( hasLchild(x) ) S.push( x->lChild ); } }

 示意图:

  先序遍历的迭代实现方法(栈)二:

template 
static void visitAlongLeftBranch( BinNodePosi(T) x, VST &visit, stack
S){ while(x){ visit(x->data); S.push(x->lChild); x=x->rChild; }}void traverse(BinNodePosi(T) x, VST &visit ){ stack
S; while(true){ //以右子树为单位,逐批访问节点 visitAlongLeftBranch(x,visit,S); //访问子树x的左侧链,右子树入栈 if(S.empty()) break; x=S.pop(); }}

图示意:

 

转载地址:http://vzbuz.baihongyu.com/

你可能感兴趣的文章
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>