import java.util.ArrayList;
class TreeNode{
int i;
TreeNode left;
TreeNode rigth;
public TreeNode(int ii){
i=ii;
}
}
public class ArrayToTree {
public static void main(String[] args){
int[][] array={{1,2},{1,3},{2,4}};
ArrayList<TreeNode> arrayLists=new ArrayList<>();
for (int i=1;i<5;i++){
arrayLists.add(new TreeNode(i));
}
int[] roots=new int[5];
int root=0;
for (int[] re:array){
TreeNode p=arrayLists.get(re[0]-1);
if (p.left==null)
p.left=arrayLists.get(re[1]-1);
else p.rigth=arrayLists.get(re[1]-1);
roots[re[1]]=1;
}
for (int i=1;i<5;i++){
if (roots[i]==0)
root=i;
}
TreeNode r=arrayLists.get(root-1);
printTree(r);
}
public static void printTree(TreeNode root){
if (root!=null) {
printTree(root.left);
System.out.print(root.i + " ");
printTree(root.rigth);
}
}
}
java 父子关系数组转二叉树
最新推荐文章于 2023-02-08 15:06:34 发布