博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
二叉树 - 前、中、后序遍历
阅读量:4331 次
发布时间:2019-06-06

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

二叉树的定义不多赘述,先贴上二叉树的代码

public class TreeNode {    int val;    TreeNode left = null;    TreeNode right = null;    public TreeNode(int val) {        // TODO Auto-generated constructor stub        this.val = val;    }}

 

前序遍历

  递归实现:

public void preOrderRecur(TreeNode root){    if(root == null)        return root;    System.out.print(head.value+" ");    preOrderRecur(head.left);    preOrderRecur(head.right);}

  非递归实现:

public void preOrderStack(TreeNode root){    if(root == null)        return root;    Stack
stack = new Stack<>(); stack.push(root); TreeNode cur = null; while(!stack.isEmpty()){ cur = stack.pop(); System.out.print(cur.val+" "); if(cur.right != null) stack.push(cur.right); if(cur.left != null) stack.push(cur.left); }}

 

中序遍历

  递归实现:

public void inOrderRecur(TreeNode root){    if(root == null)        return root;    inOrderRecur(root.left);    System.out.print(root.value+" ");    inOrderRecur(root.right);    }

  非递归实现:

public void inOrderStack(TreeNode root){    if(root == null)        return root;    Stack
stack = new Stack<>(); TreeNode cur = root; TreeNode node = null; while(cur != null){ stack.push(cur); cur = cur.left; if(cur == null){ node = stack.pop(); System.out.print(node.val+" "); cur = node.right; } } }

 

后序遍历

  递归实现:

public void posOrderRecur(TreeNode root){    if(root == null)        return root;    posOrderRecur(root.left);    posOrderRecur(root.right);    System.out.print(root.value+" ");    }

  非递归实现:

public void posOrderStack(TreeNode root){    if(root == null)        return root;    Stack
stack1 = new TreeNode<>(); Stack
stack2 = new TreeNode<>(); TreeNode cur = root; stack1.push(root); while(!s1.isEmpty()){ cur = s1.pop(); stack2.push(cur); if(cur.left != null) stack1.push(cur.left); if(cur.right != null) stack1.push(cur.right); } while(stack2.hasNext()) System.out.print(stack2.pop().val+" ");}

注:不论是递归还是非递归方法,遍历整棵树的时间复杂度都是O(N),额外的空间复杂度都是O(L),N为二叉树的节点数,L为二叉树的层数。

 

转载于:https://www.cnblogs.com/tiandiou/p/9683355.html

你可能感兴趣的文章
实验二
查看>>
shell——按指定列排序
查看>>
crash 收集
查看>>
507 LOJ 「LibreOJ NOI Round #1」接竹竿
查看>>
UI基础--烟花动画
查看>>
2018. 2.4 Java中集合嵌套集合的练习
查看>>
精通ASP.NET Web程序测试
查看>>
vue 根据不同属性 设置背景
查看>>
51Nod1601 完全图的最小生成树计数 Trie Prufer编码
查看>>
Codeforces 1110D. Jongmah 动态规划
查看>>
android驱动在win10系统上安装的心酸历程
查看>>
优雅的程序员
查看>>
oracle之三 自动任务调度
查看>>
Android dex分包方案
查看>>
ThreadLocal为什么要用WeakReference
查看>>
删除本地文件
查看>>
FOC实现概述
查看>>
base64编码的图片字节流存入html页面中的显示
查看>>
这个大学时代的博客不在维护了,请移步到我的新博客
查看>>
GUI学习之二十一——QSlider、QScroll、QDial学习总结
查看>>