【数据结构】Java实现二叉树遍历(递归)
递归实现遍历求节点数求数的深度十分简单,代码通俗易懂,但是递归来遍历的时候会产生大量的副本,在遍历一棵节点较多的树的时候,使用这种方法资源利用率不会很高
package DataStructure;
public class BinaryTreeTest {
private Node root;
class Node{
int data;
Node left;
Node right;
public Node(int data){
this.data = data;
this.left = null;
this.right= null;
}
}
//构建一棵二叉树
public BinaryTreeTest(){
root = null;
}
//二叉树添加节点
public void buildTree(Node node,int data){
if(root == null){
root = new Node(data);
}else{
if(data>node.data){
if(node.right==null){
node.right=new Node(data);
}else{
buildTree(node.right,data);
}
}else{
if(node.left==null){
node.left=new Node(data);
}else{
buildTree(node.left,data);
}
}
}
}
//递归先序遍历
public void preOrder(Node node){
if(node != null){
System.out.print(node.data+" ");
preOrder(node.left);
preOrder(node.right);
}
}
//递归中序遍历
public void inOrder(Node node){
if(node != null){
inOrder(node.left);
System.out.print(node.data+" ");
inOrder(node.right);
}
}
//递归后序遍历
public void postOrder(Node node){
if(node != null){
postOrder(node.left);
postOrder(node.right);
System.out.print(node.data+" ");
}
}
//递归树的深度
public int high(Node node){
if(node == null){
return 0;
}else{
int i = high(node.left);
int j = high(node.right);
return i>j?i+1:j+1;
}
}
//
public int size(Node node){
if(node == null){
return 0;
}else{
int i = size(node.right);
int j = size(node.left);
return i+j+1;
}
}
public static void main(String[] args){
int a[]={62,88,58,47,35,73,51,99,37,93};
BinaryTreeTest bt = new BinaryTreeTest();
for(int i=0;i<a.length;i++){
bt.buildTree(bt.root, a[i]);
}
System.out.println("先序遍历结果:");
bt.preOrder(bt.root);
System.out.println();
System.out.println("中序遍历结果:");
bt.inOrder(bt.root);
System.out.println();
System.out.println("后序遍历结果:");
bt.postOrder(bt.root);
System.out.println();
System.out.println("二叉树的深度为:"+bt.high(bt.root));
System.out.println("二叉树的节点为:"+bt.size(bt.root));
}
}
运行结果: