您的位置:首页 > 其它

二叉树的递归实现(先,中,后)

2016-06-23 15:15 183 查看
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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: