Binary Tree

1.Node节点
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;
				
	}


}

你可能感兴趣的:(binary)