定义树节点:
package 链式二叉树;
public class TreeNode {
private Object data;
private TreeNode left;
private TreeNode right;
public TreeNode() {
this.data = null;
this.left = null;
this.right = null;
}
public TreeNode(Object data, TreeNode left, TreeNode right) {
this.data = data;
this.left = left;
this.right = right;
}
public Object getData() {
return this.data;
}
public void setData(Object data) {
this.data = data;
}
public TreeNode getLeft() {
return this.left;
}
public void setLeft(TreeNode left) {
this.left = left;
}
public TreeNode getRight() {
return this.right;
}
public void setRight(TreeNode right) {
this.right = right;
}
}
二叉树实现:
package 链式二叉树;
public class BinaryTree {
public TreeNode root;
public BinaryTree(TreeNode root) {
this.root = root;
}
public BinaryTree() {
this.root = null;
}
public TreeNode getRoot() {
return this.root;
}
public void setRoot(TreeNode root) {
this.root = root;
}
//前序遍历
public void preorder(TreeNode root) {
if(root != null) {
System.out.println(root.getData());
preorder(root.getLeft());
preorder(root.getRight());
}
}
//中序遍历
public void middleorder(TreeNode root) {
if(root != null) {
middleorder(root.getLeft());
System.out.println(root.getData());
middleorder(root.getRight());
}
}
//后序遍历
public void postorder(TreeNode root) {
if(root != null) {
postorder(root.getLeft());
postorder(root.getRight());
System.out.println(root.getData());
}
}
//获得父节点
public TreeNode getParent(TreeNode ele) {
return (root == null || ele == ele) ? null : parent(root, ele);
}
private TreeNode parent(TreeNode root, TreeNode e) {
if(root == null) return null;
if(root.getLeft() == e || root.getRight() == e) return root;
TreeNode t;
return ((t = parent(root.getLeft(), e)) != null) ? t : parent(root.getRight(), e);
}
//获得节点个数
public int getSize() {
return length(root);
}
private int length(TreeNode root) {
return root == null ? 0 : (length(root.getLeft()) + length(root.getRight()) + 1);
}
//获得树的深度
public int getDepth() {
return depth(root);
}
private int depth(TreeNode root) {
if(root == null) return 0;
int m = depth(root.getLeft());
int n = depth(root.getRight());
return m > n ? m+1 : n+1;
}
public static void main(String[] args) {
TreeNode l12 = new TreeNode("left12", null, null);
TreeNode r12 = new TreeNode("right12", null, null);
TreeNode l22 = new TreeNode("left22", null, null);
TreeNode r22 = new TreeNode("right22", null, null);
TreeNode l1 = new TreeNode("left1", l12, r12);// 根节点左子树
TreeNode r1 = new TreeNode("right1", l22, r22);// 根节点右子树
TreeNode root = new TreeNode("root", l1, r1);// 创建根节点
BinaryTree bt = new BinaryTree(root);
// System.out.println("=======先序遍历======");
// bt.preorder(bt.getRoot());
// System.out.println("=======中序遍历======");
// bt.middleorder(bt.getRoot());
System.out.println("深度:"+ bt.getDepth());
}
}