二叉树01
二叉树
种类
满二叉树
定义
如果一棵二叉树只有度为0的结点和度为2的结点,并且度为0的结点在同一层上,则这棵二叉树为满二叉树。
完全二叉树
定义
在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2^(h-1) 个节点。
二叉搜索树
二叉搜索树是一个有序树。
- 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
- 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
- 它的左、右子树也分别为二叉排序树
平衡二叉搜索树
定义
又被称为AVL(Adelson-Velsky and Landis)树,且具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
遍历方式
-
深度优先遍历
- 前序遍历(递归法,迭代法)
- 中序遍历(递归法,迭代法)
- 后序遍历(递归法,迭代法)
-
广度优先遍历
- 层次遍历(迭代法)
节点定义
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int data) {
this.value = data;
}
}
递归算法
- 确定参数和返回值
- 确定终止条件
- 确定单层递归的逻辑
前序遍历
递归法
public static void preOrderRecur(Node head){//前序遍历
if(head==null){
return;
}
System.out.print(head.value+" ");//中
preOrderRecur(head.left);//前
preOrderRecur(head.right);//后
}
非递归(栈)法
public static void preOrderUnRecur(Node head){//前序遍历
System.out.println("pre-order:");
if(head!=null){
Stack<Node> stack=new Stack<Node>();
stack.add(head);
while(!stack.isEmpty()){
head=stack.pop();//pop()从栈中弹出元素
System.out.println(head.value+" ");
if(head.right!=null){
stack.push(head.right);//把右节点压入栈中
}
if(head.left!=null){
stack.push(head.left);//把右节点压入栈中
}
}
}
System.out.println();
}
中序遍历
递归法
public static void inOrderRecur(Node head){//中序遍历
if(head==null){
return;
}
inOrderRecur(head.left);
System.out.print(head.value+" ");
inOrderRecur(head.right);
}
非递归(栈)法
public static void inOrderUnRecur(Node head){//中序遍历
System.out.println("in-order:");
if(head!=null){
Stack<Node> stack=new Stack<Node>();
stack.add(head);
while(!stack.isEmpty()||head!=null){
if(head!=null){
stack.push(head);//将头节点压入栈中
head=head.left;//访问左结点,并把左节点设为新的头节点
}else{
head=stack.pop();//将头节点弹出栈
System.out.print(head.value+" ");
head=head.right;
}
}
}
System.out.println();
}
后序遍历
递归法
public static void posOrderRecur(Node head) {//后序遍历
if (head == null) {
return;
}
posOrderRecur(head.left);
posOrderRecur(head.right);
System.out.print(head.value + " ");
}
非递归(栈)法
法一
public static void posOrderUnRecur1(Node head){//后序遍历
System.out.println("pos-order:");
if(head!=null){
Stack<Node> s1=new Stack<Node>();
Stack<Node> s2=new Stack<Node>();
s1.push(head);
while(!s1.isEmpty()){
head=s1.pop();
s2.push(head);
if(head.left!=null){
s1.push(head.left);
}
if(head.right!=null){
s1.push(head.right);
}
}
while(!s2.isEmpty()){
System.out.println(s2.pop().value+" ");
}
}
System.out.println();
}
法二
public static void posOrderUnRecur2(Node h){
System.out.println("pos-order:");
if(h!=null){
Stack<Node> stack=new Stack<Node>();
stack.push(h);
Node c=null;
while(!stack.isEmpty()){
c=stack.peek();//该方法返回堆栈顶部的元素,如果堆栈为空,则返回NULL
if(c.left!=null&&h!=c.left&&h!=c.right){
stack.push(c.left);
}else if(c.right!=null&&h!=c.right){
stack.push(c.right);
}else{
System.out.print(stack.pop().value+" ");
h=c;
}
}
}
System.out.println();
}
浙公网安备 33010602011771号