您的位置:首页 > 职场人生

二叉树--面试加分

2014-11-17 23:28 211 查看
package com.briup.a10_9z.Stack_Queue;

 

//孩子双亲表示法

//每一个节点包含  数据域 左孩子 右孩子 指针变量

//如果是  威哥讲解的是什么

public class BinaryDemo {

public static void main(String[] args) {

// 客户端测试类

ManagerNode mn = new ManagerNode();

mn.addNode(8);

mn.addNode(10);

mn.addNode(20);

mn.addNode(3);

mn.addNode(5);

mn.addNode(32);

// 递归中序遍历输出

System.out.println("递归中序遍历输出:");

mn.beforePrintNode();

System.out.println();

System.out.println("递归先序遍历输出:");

mn.middlePrintNode();

System.out.println();

System.out.println("递归后序遍历输出:");

mn.afterPrintNode();

}

}

 

// 外部类 管理节点

// 因为是 二叉链表:链表形式存储,从根节点开始,可以找到下面所有子节点

class ManagerNode {

// 在这个节点管理类中需要 调用外部类Node中的方法,此时需要关联Node类

private Node root;// 关联Node类,对象一对一

 

// 添加

public void addNode(int data) {

if (root == null) {

root = new Node(data);

} else {

root.add(data);

}

}

 

// 中序遍历:左根右 记住:每一个 节点 看做 是一个对象

public void beforePrintNode() {

// 判断:保证根节点指针不是空的 才可以 继续往下遍历 输出

if (root != null) {

root.beforePrint();

}

}

 

// 先序

public void middlePrintNode() {

if (root != null) {

root.middlePrint();

}

}

 

// 后序

public void afterPrintNode() {

if (root != null) {

root.afterPrint();

}

}

}

 

// 节点类

class Node {

private int data;// 节点数据域

private Node left;// 认为是指向左孩子指针域

private Node right; // 认为是指向右孩子指针域

 

public Node(int data) {

this.data = data;

}

 

// 添加操作

// 是一个树 的逻辑结构,,数据的每一种逻辑结构 都包含 两种 物理存储结构

// 顺序存储 和非 顺序存储(链式存储、散列存储)

public void add(int data) {

/*

 * 这个传进来的 节点数据域数据大于小于当前数据 放在左子树或者右子树是自己设置的

 */

if (data < this.data) {

if (this.left == null) {

// 添加一个节点进来就是实例化一个节点对象

this.left = new Node(data);

} else {

this.left.add(data);

}

} else {

if (this.right == null) {

this.right = new Node(data);

} else {

// 递归调用

this.right.add(data);

}

}

}

 

/*

 * 递归中序遍历

 */

public void beforePrint() {

// 遍历左子树:保证左指针不是空的

if (this.left != null) {

this.left.beforePrint();// 递归操作

}

System.out.print(this.data + " ");// 输出根节点数据域

// 遍历右子树:保证 右指针不是 空的

if (this.right != null) {

this.right.beforePrint();

}

}

 

/*

 * 递归先序遍历

 */

public void middlePrint() {

// 根

System.out.print(data + " ");

// 递归遍历左子树

if (this.left != null) {

this.left.middlePrint();

}

// 递归遍历右子树

if (this.right != null) {

this.right.middlePrint();

}

}

 

/*

 * 递归后续遍历

 */

public void afterPrint() {

// 左右根

if (this.left != null) {

this.left.afterPrint();

}

if (this.right != null) {

this.right.afterPrint();

}

System.out.print(data+" ");

}

}

递归中序遍历输出:

3 5 8 10 20 32 

递归先序遍历输出:

8 3 5 10 20 32 

递归后序遍历输出:

5 3 32 20 10 8 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: