遍历二叉树

[img]http://dl2.iteye.com/upload/attachment/0098/2215/30d3192e-9329-3774-a8e1-ad35d1f42257.jpg[/img]
package com.binarytree.test;

/**
* 遍历二叉树
* @author ncs
*
*/
public class BinaryTree {

public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
TreeNode node = tree.createBinaryTree();
// 先序遍历。。。。。。。
System.out.println("**************************");
System.out.println("先序遍历。。。。。。。");
tree.xianIterator(node);
System.out.println("");
// 中序遍历。。。。。。。
System.out.println("**************************");
System.out.println("中序遍历。。。。。。。");
tree.zhongIterator(node);
System.out.println("");
// 后续遍历。。。。。。。
System.out.println("**************************");
System.out.println("后序遍历。。。。。。。");
tree.houIterator(node);
}

//创建二叉树
public TreeNode createBinaryTree() {
TreeNode D = new TreeNode("D", null, null);
TreeNode B = new TreeNode("B", D, null);
TreeNode E = new TreeNode("E", null, null);
TreeNode F = new TreeNode("F", null, null);
TreeNode C = new TreeNode("C", E, F);
TreeNode A = new TreeNode("A", B, C);
return A;
}

//先序遍历NLR N(Node)、L(Left subtree)和R(Right subtree)
public void xianIterator(TreeNode node) {
this.printNode(node);
if (node.getLeftNode() != null) {
this.xianIterator(node.getLeftNode());
}
if (node.getRightNode() != null) {
this.xianIterator(node.getRightNode());
}
}

//中序遍历LNR
public void zhongIterator(TreeNode node) {
if (node.getLeftNode() != null) {
this.zhongIterator(node.getLeftNode());
}
this.printNode(node);
if (node.getRightNode() != null) {
this.zhongIterator(node.getRightNode());
}
}

//后续遍历LRN
public void houIterator(TreeNode node) {
if (node.getLeftNode() != null) {
this.houIterator(node.getLeftNode());
}
if (node.getRightNode() != null) {
this.houIterator(node.getRightNode());
}
this.printNode(node);

}

public void printNode(TreeNode node) {
System.out.print(node.getData());
}
}

class TreeNode {
private String data;
private TreeNode leftNode;
private TreeNode rightNode;
public TreeNode(String data, TreeNode leftNode, TreeNode rightNode) {
this.data = data;
this.leftNode = leftNode;
this.rightNode = rightNode;
}

public String getData() {
return data;
}

public void setData(String data) {
this.data = data;
}

public TreeNode getLeftNode() {
return leftNode;
}

public void setLeftNode(TreeNode leftNode) {
this.leftNode = leftNode;
}

public TreeNode getRightNode() {
return rightNode;
}

public void setRightNode(TreeNode rightNode) {
this.rightNode = rightNode;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值