二叉树遍历主要分为深度遍历与广度遍历,其中深度遍历运用到的数据结构为栈,而广度优先运用的数据结构为队列。其中深度优先遍历又分为前序遍历,中序遍历以及后续遍历,广度优先又叫做层次遍历。
一 深度优先遍历
1.前序遍历 :A-B-D-F-G-H-I-C(根左右)
2.中序遍历:F-D-H-G-I-B-E-A-C(左根右)
3.后序遍历:F-H-I-G-D-E-B-C-A(左右根)
口诀可以总结出根的位置随着前中后,分别在第1,2,3的位置
4.递归实现遍历
//先序遍历的递归实现
public class PreOrder(TreeNode root){
if(!root){
visit(root);
PreOrder(root.left);
PreOrder(root.right);
}
}
//中序遍历的递归实现
public class MidOrder(TreeNode root){
if(!root){
PreOrder(root.left);
visit(root);
PreOrder(root.right);
}
}
//后序遍历的递归实现
public class LaterOrder(TreeNode root){
if(!root){
PreOrder(root.left);
PreOrder(root.right);
visit(root);
}
}
5 非递归实现遍历
//先序遍历的非递归实现
public class PreOrder(TreeNode t){
Stack<TreeNode> s = new Stack<TreeNode>();
while(t != null || !s.empty()){
while(t!=null){
s.push(t);
System.out.println(t.date);
t=t.left;
}
if(!s.empty()){
t=s.pop();
t=t.right;
}
}
}
//中序遍历的非递归实现
public class MidOrder(TreeNode t){
Stack<TreeNode> s = new Stack<TreeNode>();
while(t != null || !s.empty()){
while(t!=null){
s.push(t);
t=t.left;
}
if(!s.empty()){
t=s.pop();
System.out.println(t.date);
t=t.right;
}
}
}
5 非递归实现遍历
二 广度优先遍历
广度优先是按照二叉树的每一层顺序输出,如图按照广度优先遍历结果为A-B-C-D-E-F-G-H-I
代码如下
public static class BFS(TreeNode root){
Queue<TreeNode> queue = new LinkedList();
if(root!=null){
queue.add(root);
while(!queue.emtpy()){
TreeNode now = queue.poll();
visit(now);
f(now.left!=null){
queue.add(now.left);
}
if(now.right!=null){
queue.add(now.right);
}
}
}
}