普通二叉树实现

package shu;
package shu;

public class myNode {
	Node root;

	public myNode(Node root) {
		super();
		this.root = root;
	}
//判空
	public boolean isEmpty() {
		return root == null;
	}

	
	private void pre(Node root) {
		if (root != null) {
			// 输出root
			System.out.print(root.data+" ");
			// 输出left
			pre(root.left);
			// 输出right
			pre(root.right);
		}
		
	}
	
	public void pre(){
		System.out.println("先序遍历:");
		pre(root);
	}

	
	private int height(Node root) {
		if (root == null) {
			return 0;
		} else {
			int lh = this.height(root.left);
			int rh = this.height(root.right);
			return lh > rh ? lh + 1 : rh + 1;
		}

	}
	public int height(){
		System.out.println();
		System.out.print("高度:");
		return height(this.root);
	}
	private int size(Node root){
		if(root == null){return 0;}
		else{
			int ls = size(root.left);
			int rs = size(root.right);
			return ls+rs+1;
		}
	}
	
	public int size(){
		System.out.println();
		System.out.print("节点共有:");
		return size(root);
	}

}



package shu;

public class Node {
	Node left;
	Object data;
	Node right;
	public Node(Node left, Object data, Node right) {
		super();
		this.left = left;
		this.data = data;
		this.right = right;
	}
	
	

}

 package shu;

public class te {
	public static void main(String[] args) {
		Node n5 = new Node(null, 1, null);
		Node n4 = new Node(null, 2, null);
		Node n3 = new Node(null, 3, null);
		Node n2 = new Node(n4, 4, n5);
		Node n1 = new Node(n2, 4, n3);
		myNode m = new myNode(n1);

		System.out.println(m.isEmpty());
		m.pre();
		System.out.println(m.size());
		System.out.println(m.height());
	}

}

在这里插入图片描述

发布了41 篇原创文章 · 获赞 1 · 访问量 4732

猜你喜欢

转载自blog.csdn.net/tomorrow_shoe/article/details/96238802