java 遍历二叉树_二叉树java遍历实现

importjava.util.ArrayList;importjava.util.List;importorg.junit.Test;public classMyTree {private Node root = null;publicMyTree() {

init();

}private List list = new ArrayList();private voidinit() {

Node e= new Node("E", null, null);

Node d= new Node("D", null, null);

Node b= new Node("B", d, e);

Node c= new Node("C", null, null);

Node a= new Node("A", b, c);

root=a;

}private classNode {privateString data;privateNode lChild;privateNode rChild;publicNode(String data, Node lChild, Node rChild) {this.data =data;this.lChild =lChild;this.rChild =rChild;

}

}/*** 深度遍历

*

**/

public intgetTreeDepth(Node node) {if (node.lChild == null && node.rChild == null) {return 1;

}int left = 0, right = 0;if (node.lChild != null) {

left=getTreeDepth(node.lChild);

}if (node.rChild != null) {

right=getTreeDepth(node.rChild);

}return left > right ? left + 1 : right + 1;

}/*** 前序遍历:ABDEC

* 1.首先遍历左子树,遍历到叶子结点为止

*@return**/

public booleanpreorderTraverse(Node node) {//首先从根节点开始遍历

list.add(node);if (node.lChild != null) {//preorderTraverse(node.lChild);

}if (node.rChild != null) {

preorderTraverse(node.rChild);

}return true;

}/*** 中序遍历:DBEAC

*@return*

**/

public booleaninorderTarverse(Node node) {if (node.lChild != null) {

inorderTarverse(node.lChild);

}

list.add(node);if (node.rChild != null) {

inorderTarverse(node.rChild);

}return true;

}/*** 后序遍历:DEBCA

*@return*

**/

public booleanpostorderTarverse(Node node) {if (node.lChild != null) {

postorderTarverse(node.lChild);

}if (node.rChild != null) {

postorderTarverse(node.rChild);

}

list.add(node);return true;

}public ListgetList() {returnlist;

}

@Testpublic voidtestGetDeth() {

MyTree mt= newMyTree();

System.out.println("树的深度:" +getTreeDepth(mt.root));//if(mt.preorderTraverse(mt.root)) System.out.print("前序遍历结果:");//if(mt.inorderTarverse(mt.root)) System.out.print("中序遍历结果:");

if(mt.postorderTarverse(mt.root)) System.out.print("后序遍历结果:");//if(mt.sequenceTraverse(mt.root)) System.out.print("层序遍历结果:");

for(Node node : mt.getList()) {

System.out.print(node.data);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值