二叉树(前序,中序,后序遍历)查找
树的结点
/**
* 树的结点
*/
public class TreeNode {
private Object obj;
private TreeNode leftNode;
private TreeNode rightNode;
public TreeNode(Object obj) {
this.obj = obj;
this.leftNode=null;
this.rightNode=null;
}
public Object getObj() {
return obj;
}
public void setObj(Object obj) {
this.obj = obj;
}
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;
}
}
二叉树
public class BinaryTree {
private TreeNode root;
private TreeNode searchNode;
Scanner scanner = new Scanner(System.in);
public BinaryTree() {
System.out.println("输入!~结束输入");
this.inputTree(null);
}
public TreeNode getRoot() {
return root;
}
public void setRoot(TreeNode root) {
this.root = root;
}
public void inputTree(TreeNode node) {
if (this.root == null) {
System.out.print("请输入根节点:");
String next = scanner.next();
this.root = new TreeNode(next);
inputTree(this.root);
return;
}
System.out.print("请输入" + node.getObj() + "的左孩子节点:");
String nextL = scanner.next();
if (!"!~".equals(nextL)) {
node.setLeftNode(new TreeNode(nextL));
inputTree(node.getLeftNode());
}
System.out.print("请输入" + node.getObj() + "的右孩子节点:");
String nextR = scanner.next();
if (!"!~".equals(nextR)) {
node.setRightNode(new TreeNode(nextR));
inputTree(node.getRightNode());
}
}
/**
* 前序遍历
*/
public void preorderTraversal(TreeNode node) {
if (node == null) return;
else {
System.out.print(node.getObj() + " ");
preorderTraversal(node.getLeftNode());
preorderTraversal(node.getRightNode());
}
}
/**
* 中序遍历
*/
public void inOrderTraversal(TreeNode node) {
if (node == null) return;
else {
inOrderTraversal(node.getLeftNode());
System.out.print(node.getObj() + " ");
inOrderTraversal(node.getRightNode());
}
}
/**
* 后序遍历
*/
public void postOrderTraversal(TreeNode node) {
if (node == null) return;
else {
postOrderTraversal(node.getLeftNode());
postOrderTraversal(node.getRightNode());
System.out.print(node.getObj() + " ");
}
}
/**
* 查找
*/
public TreeNode searchNode(Object object){
preorderSearch(this.root,object);
return searchNode;
}
/**
* 用于查找遍历
*/
public void preorderSearch(TreeNode node,Object object){
if (searchNode!=null||node==null) return ;
else {
if (node.getObj().equals(object)) this.searchNode=node;
preorderSearch(node.getLeftNode(),object);
preorderSearch(node.getRightNode(),object);
}
}
}