1、二叉树
2、二叉树的遍历
注意:这里说的前序、中序、后序都是相对根节点来说的
1、二叉树的遍历(以前序遍历为例)
二叉树的前序遍历是指从根节点开始对于每一个子树,先对根节点进行遍历,再对左右孩子节点进行遍历。
class TreeNode {
private int no;
private String name;
private TreeNode left;//默认为null
private TreeNode right;//默认为null
public TreeNode(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 void setName(String name) {
this.name = name;
}
public TreeNode getLeft() {
return left;
}
public void setLeft(TreeNode left) {
this.left = left;
}
public TreeNode getRight() {
return right;
}
public void setRight(TreeNode right) {
this.right = right;
}
@Override
public String toString() {
return "TreeNode{" + "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();
}
}
/**
*
* @param no 按查找
* @return 如果找到返回该Node,否则返回null
*/
public TreeNode preOrderSearch(int no) {
if (this.no == no) {//比较当前节点
return this;
}
TreeNode resNode = null;
if (this.left != null) {//判断左节点是否为空,不为空则递归前序查找
resNode = this.left.preOrderSearch(no);
}
if (resNode != null) {//向左递归找到了
return resNode;
}
if (this.right != null) {//向左递归未找到,判断右节点是否为空,不为空则递归前序查找
resNode = this .right.preOrderSearch(no);
}
return resNode;
}
}
定义二叉树
class BinaryTree {
private TreeNode root;
public void setRoot(TreeNode root) {
this.root = root;
}
//前序遍历
public void preOrder() {
if (this.root != null) {
this.root.preOrder();
} else {
System.out.println("二叉树为空!");
}
}
//前序遍历查找
public TreeNode preOrderSearch(int no) {
if (root != null) {
return root.preOrderSearch(no);
} else {
return null;
}
}
}
public class BinaryTreeDemo {
public static void main(String[] args) {
BinaryTree binaryTree = new BinaryTree();
TreeNode root = new TreeNode(1, "张三");
TreeNode node2 = new TreeNode(2, "李四");
TreeNode node3 = new TreeNode(3, "王五");
TreeNode node4 = new TreeNode(4, "小明");
TreeNode node5 = new TreeNode(5, "小红");
//手动创建二叉树
root.setLeft(node2);
root.setRight(node3);
node3.setRight(node4);
node3.setLeft(node5);
binaryTree.setRoot(root);
//测试
System.out.println("前序遍历:");
binaryTree.preOrder();
}
System.out.println("前序遍历查找:");
TreeNode resNode = binaryTree.preOrderSearch(3);
if (resNode != null) {
System.out.println(resNode);
}
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- ovod.cn 版权所有 湘ICP备2023023988号-4
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务