博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
二叉树的遍历
阅读量:3966 次
发布时间:2019-05-24

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

package com.chenjian;import java.util.Stack;import java.util.HashMap;public class BinTree {
private char date; private BinTree lchild; private BinTree rchild; public BinTree(char c) {
date = c; } // 先序遍历递归 public static void preOrder(BinTree t) {
if (t == null) {
return; } System.out.print(t.date); preOrder(t.lchild); preOrder(t.rchild); } // 中序遍历递归 public static void InOrder(BinTree t) {
if (t == null) {
return; } InOrder(t.lchild); System.out.print(t.date); InOrder(t.rchild); } // 后序遍历递归 public static void PostOrder(BinTree t) {
if (t == null) {
return; } PostOrder(t.lchild); PostOrder(t.rchild); System.out.print(t.date); } // 先序遍历非递归 public static void preOrder2(BinTree t) {
Stack
s = new Stack
(); while (t != null || !s.empty()) {
while (t != null) {
System.out.print(t.date); s.push(t); t = t.lchild; } if (!s.empty()) {
t = s.pop(); t = t.rchild; } } } // 中序遍历非递归 public static void InOrder2(BinTree t) {
Stack
s = new Stack
(); while (t != null || !s.empty()) {
while (t != null) {
s.push(t); t = t.lchild; } if (!s.empty()) {
t = s.pop(); System.out.print(t.date); t = t.rchild; } } } // 后序遍历非递归 public static void PostOrder2(BinTree t) {
Stack
s = new Stack
(); Stack
s2 = new Stack
(); Integer i = new Integer(1); while (t != null || !s.empty()) { while (t != null) { s.push(t); s2.push(new Integer(0)); t = t.lchild; } while (!s.empty() && s2.peek().equals(i)) { s2.pop(); System.out.print(s.pop().date); } if (!s.empty()) { s2.pop(); s2.push(new Integer(1)); t = s.peek(); t = t.rchild; } } } public static void main(String[] args) { BinTree b1 = new BinTree('a'); BinTree b2 = new BinTree('b'); BinTree b3 = new BinTree('c'); BinTree b4 = new BinTree('d'); BinTree b5 = new BinTree('e'); /** * a * / / * b c * / / * d e */ b1.lchild = b2; b1.rchild = b3; b2.lchild = b4; b2.rchild = b5; BinTree.preOrder(b1); System.out.println(); BinTree.preOrder2(b1); System.out.println(); BinTree.InOrder(b1); System.out.println(); BinTree.InOrder2(b1); System.out.println(); BinTree.PostOrder(b1); System.out.println(); BinTree.PostOrder2(b1); }}

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

你可能感兴趣的文章
Watir2.0.1之——屏幕截图
查看>>
Ruby+Watir经验谈: Understanding Watir
查看>>
watir + autoit3
查看>>
Ruby+Watir安装
查看>>
(原博客转移)诺基亚手机成板砖无法开机后,强刷修复手机系统的方法!本人亲测
查看>>
Ruby使用Win32API来操作鼠标
查看>>
代替Watir中click_no_wait的方法——left_click
查看>>
autoit3 ie.au3 函数之——_IE_Example、_IE_Introduction
查看>>
Android开发之——自定义标题栏titlebar
查看>>
autoit3 ie.au3 函数之——_IE_VersionInfo
查看>>
autoit3 ie.au3 函数之——_IEAction
查看>>
autoit3 ie.au3 函数之——_IEGetObjById、_IEGetObjByName
查看>>
autoit3 ie.au3 函数之——_IEAttach
查看>>
autoit3 ie.au3 函数之——_IEBodyReadHTML、_IEBodyWriteHTML
查看>>
autoit3 ie.au3 函数之——_IEBodyReadText
查看>>
autoit3 ie.au3 函数之——_IECreate
查看>>
autoit3 ie.au3 函数之——_IECreateEmbedded
查看>>
autoit3 ie.au3 函数之——_IEDocGetObj
查看>>
autoit3 ie.au3 函数之——_IEDocInsertHTML
查看>>
autoit3 ie.au3 函数之——_IEDocWriteHTML
查看>>