Skip to content
This repository was archived by the owner on May 22, 2026. It is now read-only.

Commit 12343e2

Browse files
Merge pull request #18 from RyosukeDTomita/feature/tree
feat: how to find parent
2 parents 49fb756 + efab641 commit 12343e2

1 file changed

Lines changed: 19 additions & 0 deletions

File tree

data_structure/tree/tree.hs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import Data.List (find)
2+
13
data Tree a = Node a [Tree a] deriving (Show) -- 型コンストラクタとしてTreeをデータコンストラクタとしてNodeを作成
24

35
-- 葉ノード(子を持たないノード)を作成
@@ -38,6 +40,19 @@ depth :: Tree a -> Int
3840
depth (Node _ []) = 1
3941
depth (Node _ children) = 1 + maximum (map depth children)
4042

43+
-- ある要素から見た親を探す
44+
findParent :: (Eq a, Num a) => Tree a -> a -> a
45+
findParent (Node x children) v
46+
| v `elem` map rootValue children = x
47+
| otherwise =
48+
foldr
49+
( \child acc -> case findParent child v of
50+
-1 -> acc
51+
p -> p
52+
)
53+
(-1)
54+
children
55+
4156
-- 木を整形して表示(枝を使って階層構造を明確化)
4257
prettyPrint :: (Show a) => Tree a -> String
4358
prettyPrint tree = go "" "" tree
@@ -73,3 +88,7 @@ main = do
7388
let tree3 = delete 2 tree2
7489
print tree3
7590
putStr $ prettyPrint tree3
91+
92+
-- 親を探す
93+
let parentOf4 = findParent tree2 4
94+
print parentOf4

0 commit comments

Comments
 (0)