java 数组构造_java – 从数组构造(非二进制)树

我需要用Java构建一个树.我已经完成了树作为数据结构.但是我在将数据从数组提供给树时遇到了一些问题.这是我需要做的.

domain = {"b", "c"};

那么,树应该像:

null -> b,c

b->c c->b

所以基本上我希望节点的子节点拥有来自域的所有子节点中尚未覆盖的子节点.问题是,尽管有很多尝试,但我无法编写代码来执行此操作.我知道它可以用递归函数完成.

我不想要完整的代码.对解决方案的任何暗示都将受到高度赞赏.谢谢.

附:

我清楚说明了. “”树中的每个节点都具有来自域的子节点的所有值,除了已经覆盖的子节点或其父节点“”

如图所示,a是基数(比如null).它具有域(b,c)中的所有值. b有c,c有b.

解决方法:

规范说:

Every node in the tree has all the values as children from the domain apart from the ones that are already covered in it or its parents

它有点不清楚,但我假设它覆盖在它或它的父节点意味着如果值x不在从节点到根的路径上,则允许值为x的节点.在这种情况下,树可以像这样构造(语言是Haskell):

import List

data Tree = Tree String [Tree]

build x xs = Tree x children

where

children = map (\x -> build x (delete x xs)) xs

例如,给定根值“a”和域值列表[“b”,“c”,“d”],程序构造一个值为“a”的根节点,并且递归地构造3个子节点:

>根值“b”和域[“c”,“d”],

>根值“c”和域[“b”,“d”],

>和根值“d”和域[“b”,“c”].

在伪Python中,这是Haskell程序的算法:

def build(root_value, domain):

node = Tree(root_value)

# For each value in the domain:

for i in range(len(domain)):

child_root = domain[i]

# The child domain is equal to the original domain

# with value at position 'i' removed.

child_domain = domain[: i] + domain[i + 1:]

# Recursively build the child

child = build(child_root, child_domain)

# - and add the child to the node.

node.add_child(child)

return node

这是对构建函数的测试,它打印问题示例的树和上面的示例:

pretty level (Tree x children) = do

mapM_ putStr [indent, x, "\n"]

mapM_ (pretty (level + 3)) children

where

indent = replicate level ' '

main = do

putStrLn "Tree for a -> b, c:"

pretty 0 (build "a" ["b", "c"])

putStrLn "\nTree for a -> b, c, d:"

pretty 0 (build "a" ["b", "c", "d"])

测试使用缩进来显示树中每个节点的深度:

Tree for a -> b, c:

a

b

c

c

b

Tree for a -> b, c, d:

a

b

c

d

d

c

c

b

d

d

b

d

b

c

c

b

标签:java,data-structures,tree

来源: https://codeday.me/bug/20190709/1418342.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值