1.Node节点
2.
package BinaryTree;
public class Node{
int data;
Node right;
Node left;
Node(int data) {
super();
this.data = data;
}
Node(int data, Node right, Node left) {
super();
this.data = data;
this.right = right;
this.left = left;
}
}2.
package BinaryTree;
public class BinaryTree {
Node root;
/**
* 镜像,交换子树
* @param node
*/
public void swap(Node node){
if(node == null)
return;
if(node.left == null && node.right == null)
return;
Node tmp = node.left;
node.left = node.right;
node.right = tmp;
swap(node.left);
swap(node.right);
}
/**
* 插入节点
* @param node
* @param data
* @return
*/
public Node insert(Node node,int data){
if(node == null){
node = new Node(data);
}else{
if(data <= node.data)
insert(node.left,data);
else
insert(node.right,data);
}
return node;
}
/**
* 遍历二叉树,中序
* @param node
*/
public void printNode(Node node){
if(node == null)
return;
printNode(node.left);
System.out.println(node.data);
printNode(node.right);
}
/**
* 二叉树元素个数
* @param node
* @return
*/
public int size(Node node){
if(node == null)
return 0;
return size(node.left)+1+size(node.right);
}
/**
* 二叉树深度
* @param node
* @return
*/
public int depth(Node node){
if(node == null)
return 0;
int childdepth = depth(node.left)>depth(node.right)?depth(node.left):depth(node.right);
return 1+childdepth;
}
}

本文介绍了一个简单的二叉树类的实现,包括节点插入、树的遍历、节点数量计算及树深度计算等功能,并提供了镜像操作的方法。
2055

被折叠的 条评论
为什么被折叠?



