二叉树的四种遍历算法实现,没你想得那么难
2020-12-13 05:51
标签:poll oid comment his 左右子树 pre linked 出队 ams 我用下图的树为例,做树的遍历: 树节点的定义: 输出结果: 输出结果: 输出结果: 有没有觉得树的先序,中序,后序遍历都非常简单,递归三行代码就搞定了。好吧,下边厉害的要来了 层序遍历:所有深度为D的节点要在深度为D+1的节点之前进行处理,层序遍历与其他类型的遍历不同的地方在于它不是递归地执行的,它用到队列,而不使用递归所默示的栈。 算法思想:二叉树的遍历
二叉树结构
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
public TreeNode(int val, TreeNode left, TreeNode right) {
super();
this.val = val;
this.left = left;
this.right = right;
}}树的结构的代码实现:public static void main(String[] args) {
TreeNode e = new TreeNode(1);
TreeNode g = new TreeNode(2);
TreeNode h = new TreeNode(3);
TreeNode i = new TreeNode(4);
TreeNode d = new TreeNode(5,null,g);
TreeNode f = new TreeNode(6,h,i);
TreeNode b = new TreeNode(7,d,e);
TreeNode c = new TreeNode(8,f,null);
TreeNode root = new TreeNode(9,b,c);}
中序遍历
public static void printTree(TreeNode t){
if(t!=null){
printTree(t.left);
System.out.print(t.val+" ");
printTree(t.right);
}
}
5 2 7 1 9 3 6 4 8后序遍历
public static void printTree(TreeNode t){
if(t!=null){
printTree(t.left);
printTree(t.right);
System.out.print(t.val+" ");
}
}
2 5 1 7 3 4 6 8 9先序遍历
public static void printTree(TreeNode t){
if(t!=null){
System.out.print(t.val+" ");
printTree(t.left);
printTree(t.right);
}
}
9 7 5 2 1 8 6 3 4
层序遍历
package Tree;import java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.Queue;/* * 层序遍历 * */public class TreePrinter1 {
public static int[][] printTree(TreeNode root) {
List > list = new ArrayList >();
list.add(new ArrayList
输出结果:
9
7 8
5 1 6
2 3 4
二叉树的四种遍历算法实现,没你想得那么难
标签:poll oid comment his 左右子树 pre linked 出队 ams
原文地址:https://www.cnblogs.com/bianchengrufeng/p/11152890.html