二叉树介绍:
二叉树(Binary tree)是一种重要的树形结构,常用于解决许多实际问题中的基本数据结构问题。它的定义如下:
每个节点最多有两棵子树(称为左子树和右子树),且节点要么是叶子节点(空节点,即没有左子树和右子树),要么至少有一个子节点。
什么是前序中序后序遍历
前序遍历: 头左右 1 2 4 5 3 6 7
中序遍历:左头右 4 2 5 1 6 3 7
后序遍历:左右头. 4 5 2 6 7 3 1
都是以头节点为参照物来定这个顺序的
定义一个二叉树的结构.
public class Node{
int val;
Node left;
Node right;
public Node(int val) {
this.val = val;
}
}
前序遍历
递归实现
public static void pre(Node head){
if (head == null){
return ;
}
System.out.println(head.val+" ");
pre(head.left);
pre(head.right);
}
非递归实现
/**
* 非递归的方式 进行先序遍历 头左右/
* @param head
*/
public static void pre(Node head){
if (head == null){
return ;
}
Stack<Node> nodes = new Stack<>();
//先把头压进栈
nodes.push(head);
while (!nodes.isEmpty()){
Node pop = nodes.pop();
System.out.print(pop.val+" ");
if (pop.right != null){
nodes.push(pop.right);
}
if (pop.left != null){
nodes.push(pop.left);
}
}
System.out.println();
}
中序遍历
递归实现
public static void in(Node head){
if (head == null){
return ;
}
pre(head.left);
System.out.println(head.val+" ");
pre(head.right);
}
非递归实现
public static void in(Node head){
if (head == null){
return ;
}
Stack<Node> nodes = new Stack<>();
while (!nodes.isEmpty() || head != null){
if (head != null){
nodes.push(head);
head = head.left;
}else{
head = nodes.pop();
System.out.print(head.val+" ");
head = head.right;
}
}
System.out.println();
}
后序遍历
递归实现
public static void pos(Node head){
if (head == null){
return ;
}
pre(head.left);
pre(head.right);
System.out.print(head.val+" ");
}
非递归实现
/**
* 后序遍历
* @param head
*/
public static void pos(Node head){
if (head == null){
return;
}
Stack<Node> nodes = new Stack<>();
nodes.add(head);
Stack<Node> help = new Stack<>();
while (!nodes.isEmpty()){
Node pop = nodes.pop();
help.push(pop);
if (pop.left != null){
nodes.push(pop.left);
}
if (pop.right != null){
nodes.push(pop.right);
}
}
while (!help.isEmpty()){
System.out.print(help.pop().val+" ");
}
System.out.println();
}