树和二叉树的区别:树种节点的最大度数没有限制,二叉树节点的最大度数为2。二叉树的节点有左右之分,也就是是有序树。
一个深度为K的满二叉树,包含了2^k-1个节点。完全二叉树是左边或者右边缺少若干连续的节点。
二叉排序树:如果左子树不为空左子树的节点都小于根节点,右子树反之,左右子树也分别为二叉排序树。
深度优先算法:有三种:
先序遍历:OLR o是root L是left R是right
中序遍历:LOR
后序遍历:LRO
因为二叉树定义本身就有递归性,所有深度优先算法非常方便的使用递归来实现每个节点的遍历。
Java代码:这里只实现先序遍历
/*
* 二叉树插入数据和深度优先算法
*/
public class BinaryTree {
public static void main(String[] args) {
BinaryTree b=new BinaryTree();
int []data={2,8,7,4,9,3,1,6,7,5};
b.BuildTree(data);
b.firOrder();
}
private Node root;
//根节点为空
public BinaryTree(){
root=null;
}
//将数据插入到二叉树中
public void insert(int data){
Node node=new Node(data);
//根节点为空,则数据充当根节点
if(root==null){
root=node;
}else{
Node cuurent=root;
Node parent;
//循环遍历来将元素插入到合适位置
while (true) {
parent=cuurent;
//将元素小于父节点的元素放入到左子树上
if(data<cuurent.data){
//将下面的节点保存下来,如果节点不为空,则继续遍历下一个节点
cuurent=cuurent.left;
//如果该节点空就放入到该节点上面
if(cuurent==null){
parent.left=node;
return;
}
}else {//将元素大于父节点的元素放入到右子树上
cuurent=cuurent.right;
if(cuurent==null){
parent.right=node;
return;
}
}
}
}
}
/*
* 将数据输入到二叉树里面
*/
public void BuildTree(int []data){
for(int i=0;i<data.length;i++){
insert(data[i]);
}
}
/*
* 深度优先算法里面的先序遍历方法递归实现
*/
public void firOrder(){
this.firOrder(this.root);
}
public void firOrder(Node localRoot){
if(localRoot!=null){
//先输出根节点
System.out.print(localRoot.data+" ");
//左子树节点
firOrder(localRoot.left);
//右子树节点
firOrder(localRoot.right);
}
}
}
/*
* 链表实现二叉树
*/
class Node{
public int data;
public Node left;
public Node right;
public Node(int data){
this.data=data;
this.left=left;
this.right=right;
}
}