【问题标题】:Finding element in a binary tree在二叉树中查找元素
【发布时间】:2013-01-07 14:24:51
【问题描述】:

假设我有一棵二叉树:

data Bst a = Empty | Node (Bst a) a (Bst a)

我必须编写一个函数来搜索一个值并返回其子项的数量。如果没有具有此值的节点,则返回 -1。我试图同时编写 BFS 和 DFS,但都失败了。

【问题讨论】:

  • 请向我们展示您尝试的代码,这将帮助我们查明哪里出了问题。
  • Haskell 也使用Maybe a = Nothing | Just a 来表示没有找到一个元素。
  • 查看Tree 实现here。有称为treeInserttreeElem 的函数。他们可以直观地了解如何遍历树来实现您的功能。

标签: search haskell tree find binary-tree


【解决方案1】:

模式匹配是你的朋友。您的Bst 可以是EmptyNode,因此在顶层,您的search 函数将是

search Empty = ...
search (Node left x right) = ...

Empty 树可能包含目标值吗?对于Node,目标值(如果存在)将是节点值(上面的x)、left 子树、right 子树中的节点值,或者可能是这些的某种组合。

“返回[ing]其子代的数量”,我假设您的意思是 Bst 的子代总数,其根植于 Node,其值为目标,这是一个有趣的问题组合。您将需要 另一个 函数,例如 numChildren,其定义使用上述模式匹配。注意事项:

  1. Empty 树有多少个后代?
  2. Node 的情况下,x 不算数,因为您想要后代。如果你有一个函数来计算 leftright 子树中的子树数量……

【讨论】:

  • 我想补充一点,他需要的另一个神奇词是recursion。通过模式匹配和递归,分配非常容易。
【解决方案2】:

这是一种方法。呼吸优先搜索实际上可能有点难以实现,而且这个解决方案 (findBFS) 非常复杂(附加到列表是 O(n)),但你会明白要点的。

首先,我决定拆分查找函数以返回节点元素匹配的树。这简化了拆分计数功能。另外,返回元素的数量比返回后代的数量更容易,如果找不到则返回 -1,因此numDesc 函数依赖于 numElements 函数。

data Tree a = Empty
            | Node a (Tree a) (Tree a)

numElements :: Tree a -> Int
numElements Empty        = 0
numElements (Node _ l r) = 1 + numElements l + numElements r

findDFS :: Eq a => a -> Tree a -> Tree a
findDFS _ Empty                         = Empty
findDFS x node@(Node y l r) | x == y    = node
                            | otherwise = case findDFS x l of 
                                            node'@(Node _ _ _) -> node'
                                            Empty              -> findDFS x r

findBFS :: Eq a => a -> [Tree a] -> Tree a                                                                
findBFS x []                              = Empty
findBFS x ((Empty):ts)                    = findBFS x ts
findBFS x (node@(Node y _ _):ts) | x == y = node
findBFS x ((Node _ l r):ts)               = findBFS x (ts ++ [l,r])

numDescDFS :: Eq a => a -> Tree a -> Int
numDescDFS x t = numElements (findDFS x t) - 1

numDescBFS :: Eq a => a -> Tree a -> Int
numDescBFS x t = numElements (findBFS x [t]) - 1

【讨论】:

  • 我无法理解otherwise 之后发生了什么...你能解释一下吗?
猜你喜欢
  • 1970-01-01
  • 2012-10-29
  • 1970-01-01
  • 2014-03-05
  • 2021-09-10
  • 1970-01-01
  • 2016-10-21
  • 1970-01-01
相关资源
最近更新 更多