根据长度为n的数组生成n层深度的数据结构

有一个不定长的数组,数组中有n个字符串,要求实现:第1个元素是第0个元素的子元素,第2个元素是第一个元素的子元素,第3个元素是第二个元素的子元素,依次类推,最后输出父子结构的元素。

如:[1,2,3,4]

输出 {
        1 : children{
            2 : children{
                3 : children{
                    4
                }
            }
        }
    }

这个数据结构是树状结构,可以参考

import java.util.LinkedList;
import java.util.List;
class TreeNode{
	int val;
	TreeNode left;
	TreeNode right;
	TreeNode(int x){
		val = x;
	}
}

public class test1 {
	public static int[] array = {1, 2, 3, 4, 5, 6, 7};
	public static List<TreeNode> nodeList = new LinkedList<TreeNode>();
	public static void createBinTree() {
		//并把数组中的值都转化为树结点的值,存储到list中
		for(int i = 0; i < array.length; i++) {
			nodeList.add(new TreeNode(array[i]));
		}
		for(int j = 0; j < array.length/2 - 1; j++) {
			//左孩子
			nodeList.get(j).left = nodeList.get(j*2 + 1);
			//右孩子
			nodeList.get(j).right = nodeList.get(j*2 + 2);
		}
		
		//最后一个父结点,可能没有右孩子
		int lastParent = array.length / 2 - 1;
		//所以,先处理左孩子
		nodeList.get(lastParent).left = nodeList.get(lastParent*2 + 1);
		//如果数组长度为奇数,那么就建立右孩子
		if(array.length % 2 == 1) {
			nodeList.get(lastParent).right = nodeList.get(lastParent*2 + 2);
		}
		
	}
	public static void inorder(TreeNode root) {
		if(root == null)
			return;
		System.out.print(root.val + " ");
		inorder(root.left);
		inorder(root.right);
	}
	
	public static void main(String[] args) {
		createBinTree();
		//第一个结点就是根结点
		TreeNode root = nodeList.get(0);
		inorder(root);
	}
}

 

用链表实现:

class Node{

   String data;

  Node next;

}

您好,我是有问必答小助手,你的问题已经有小伙伴为您解答了问题,您看下是否解决了您的问题,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632

非常感谢您使用有问必答服务,为了后续更快速的帮您解决问题,现诚邀您参与有问必答体验反馈。您的建议将会运用到我们的产品优化中,希望能得到您的支持与协助!

速戳参与调研>>>https://t.csdnimg.cn/Kf0y