package erchashu;
import java.util.ArrayList;
import java.util.List;
public class diguierchashu {
public static List<TreeNode> list1 =new ArrayList<TreeNode>();
public static List<TreeNode> list2 =new ArrayList<TreeNode>();
public static List<TreeNode> list3 =new ArrayList<TreeNode>();
public static void main(String[] args) {
TreeNode l1 =new TreeNode(1);
TreeNode l2 =new TreeNode(2);
TreeNode l3 =new TreeNode(3);
TreeNode l4 =new TreeNode(4);
TreeNode l5 =new TreeNode(5);
TreeNode l6 =new TreeNode(6);
TreeNode l7 =new TreeNode(7);
l1.left =l2;
l1.right =l3;
l2.left =l4;
l2.right =l5;
l3.left =l6;
l3.right =l7;
List<List<TreeNode>> list =new ArrayList<List<TreeNode>>();
diguierchashu.convert(l1);
list.add(list1);
list.add(list2);
list.add(list3);
for(int i=0;i<list.size();i++){
for(int j=0;j<list.get(i).size();j++){
System.out.print(list.get(i).get(j).val);
}
System.out.println("^_^");
}
}
public static void convert(TreeNode root) {
xianxu(root);
zhongxu(root);
houxu(root);
}
public static void houxu(TreeNode root) {
if(root == null){
return ;
}
houxu(root.left);
houxu(root.right);
list3.add(root);
}
public static void zhongxu(TreeNode root) {
if(root == null){
return ;
}
zhongxu(root.left);
list2.add(root);
zhongxu(root.right);
}
public static void xianxu(TreeNode root) {
if(root == null){
return ;
}
list1.add(root);
xianxu(root.left);
xianxu(root.right);
}
static class TreeNode{
int val = 0;
TreeNode left = null;
TreeNode right = null;
TreeNode(int val){
this.val = val;
}
}
}二叉树的递归实现(先,中,后)
最新推荐文章于 2024-08-17 16:30:25 发布
本文介绍了一种使用Java实现二叉树先序、中序及后序遍历的方法,并通过具体实例展示了如何构建一棵二叉树并进行不同方式的遍历。文章通过创建节点并连接它们来形成一棵完整的二叉树,然后分别使用递归函数实现了三种遍历方式,并将结果存储到不同的列表中以便展示。
1243

被折叠的 条评论
为什么被折叠?



