有趣的二叉树
Posted *平芜尽处是春山*
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了有趣的二叉树相关的知识,希望对你有一定的参考价值。
有趣的二叉树
思路:
1、自定义一个有趣的二叉树
2、按照前、中、后序三种遍历,并删除一个结点
给出图片:
代码实现:
public class BinaryTreeTest
public static void main(String[] args)
BinaryTree binaryTree = new BinaryTree();
PeopleNode root = new PeopleNode(1,"林黛玉");
PeopleNode node2 = new PeopleNode(2,"司马懿");
PeopleNode node3= new PeopleNode(3,"薛宝钗");
PeopleNode node4= new PeopleNode(4,"诸葛亮");
PeopleNode node5= new PeopleNode(5,"武媚娘");
root.setLeft(node2);
root.setRight(node3);
node3.setLeft(node4);
node3.setRight(node5);
binaryTree.setRoot(root);
System.out.println("前序遍历");
binaryTree.preOrder();
System.out.println("中序遍历");
binaryTree.midOrder();
System.out.println("后序遍历");
binaryTree.postOrder();
binaryTree.delNode(2);
System.out.println("删除结点2,前序遍历");
binaryTree.preOrder();
class BinaryTree
private PeopleNode root;
public PeopleNode getRoot()
return root;
public void setRoot(PeopleNode root)
this.root = root;
public void preOrder()
if(this.root != null)
this.root.preOrder();
else
System.out.println("二叉树为空,不能遍历");
public void midOrder()
if(this.root != null)
this.root.midOrder();
else
System.out.println("二叉树为空,不能遍历");
public void postOrder()
if(this.root != null)
this.root.postOrder();
else
System.out.println("二叉树为空,不能遍历");
public void delNode(int no)
if(root != null)
if(root.getNo() == no)
root = null;
else
root.delNode(no);
else
System.out.println("空树,不能删除");
class PeopleNode
private int no;
private String name;
private PeopleNode left;
private PeopleNode right;
public PeopleNode(int no, String name)
this.no = no;
this.name = name;
public int getNo()
return no;
public void setNo(int no)
this.no = no;
public String getName()
return name;
public String setName(String name)
return this.name = name;
public PeopleNode getLeft()
return left;
public void setLeft(PeopleNode left)
this.left = left;
public PeopleNode getRight()
return right;
public void setRight(PeopleNode right)
this.right = right;
@Override
public String toString()
return "PeopleNode[No=" + no + ",name=" + name + "]";
public void preOrder()
System.out.println(this);
if (this.left != null)
this.left.preOrder();
if (this.right != null)
this.right.preOrder();
public void midOrder()
if (this.left != null)
this.left.midOrder();
System.out.println(this);
if (this.right != null)
this.right.midOrder();
public void postOrder()
if (this.left != null)
this.left.postOrder();
if (this.right != null)
this.right.postOrder();
System.out.println(this);
public void delNode(int no)
if (this.left != null && this.left.no == no)
this.left = null;
return;
if (this.right != null && this.right.no == no)
this.right = null;
return;
if (this.left != null)
this.left.delNode(no);
if (this.right != null)
this.right.delNode(no);
运行截图:
以上是关于有趣的二叉树的主要内容,如果未能解决你的问题,请参考以下文章