학습용으로 haskell을 배웠습니다. 이진 트리를 작성하기로했습니다.이진 트리 구조에서 스택 오버플로를 피하십시오.
까지 내가 이해할 수있는 것처럼 삽입과 삭제의 큰 세트는 결과 트리가 상대적으로 작더라도 마침내 평가를 시작할 때 스택 오버플로에 쉽게 도달 할 수 있습니다.
여기 내 질문은 다음과 같습니다
난 내 기능에 약간의 엄격함을 도입하여이를 방지 할 수 있습니까? (뭔가 seq/deepseq?).
상황에 따라 현재 상태에서 삽입/삭제를 유지하고 싶습니까?
내가 잘못 설계 한 것으로 느껴지면 코드를 수정하고 개선하십시오.
관련 코드 :
import Data.List
data Tree a = Empty | Branch a (Tree a) (Tree a)
deriving (Eq)
leaf x = Branch x Empty Empty
-- insert ------------------------------------
treeInsert :: (Eq a, Ord a) => Tree a -> a -> Tree a
treeInsert Empty x = leaf x
treeInsert (Branch y l r) x | x<y = Branch y (treeInsert l x) r
| x>y = Branch y l (treeInsert r x)
| otherwise = Branch x l r --edit
-- delete ------------------------------------
treeDelete :: (Eq a, Ord a) => Tree a -> a -> Tree a
treeDelete Empty _ = Empty
treeDelete (Branch y l r) x | y<x = Branch y l (treeDelete r x)
| y>x = Branch y (treeDelete l x) r
| y==x = del' $ Branch y l r
where
-- if this Branch is a leaf dispose of it.
-- if branch has only one child return the child (skip over).
-- otherwise, replace this branch with its successor (the leftmost child of the right tree)
-- successor will be extracted from its original location.
del' (Branch y Empty Empty) = Empty
del' (Branch y Empty r) = r
del' (Branch y l Empty) = l
del' (Branch y l r) = Branch ySucc l rWithout_ySucc
where
(rWithout_ySucc, ySucc) = leftmost r
where
leftmost (Branch y Empty Empty) = (Empty, y)
leftmost (Branch y Empty r) = (r, y)
leftmost (Branch y l r) = (Branch y ll r, z) where (ll, z) = leftmost l
'treeInsert'가 의도 한대로 작동하지 않는다고 생각합니다. – augustss
@augustss 제발 정교하게 – jajdoo
물건이 삽입 된 항목이 이미있을 때 무엇을합니까? – augustss