Let us call a binary tree symmetric if you can draw a vertical line through the root node and then the right subtree is the mirror image of the left subtree. Write a predicate symmetric/1 to check whether a given binary tree is symmetric. Hint: Write a predicate mirror/2 first to check whether one tree is the mirror image of another. We are only interested in the structure, not in the contents of the nodes.
构造一颗树这棵树从root处对称
Example in Haskell:
λ> symmetric (Branch 'x' (Branch 'x' Empty Empty) Empty)
False
λ> symmetric (Branch 'x' (Branch 'x' Empty Empty) (Branch 'x' Empty Empty))
True
answer:
mirror Empty Empty = True
mirror (Branch _ a b) (Branch _ x y) = mirror a y && mirror b x
mirror _ _ = False
symmetric Empty = True
symmetric (Branch _ l r) = mirror l r
思路:
Haskell就是一个抽丝剥茧的过程, 要从最基本的规则出发,所以我们需要去表达最基本的规则。
- 什么是symmetric, 首先,左边的树需要等于右边的树,从根出发的两棵树是什么状况:mirror (Branch _ a b) (Branch _ x y) = mirror a y && mirror b x
- 最基本的状况是什么就是一层层往下,总会有empty,最底部是什么样子?mirror Empty Empty = True
- 有没有别的情况,其他情况是错误的吗?
- 当我们选择按照模式来完成Haskell,这个思路是通常的步骤。
binary search tree
左树必右树所有的node数值小
Use the predicate add/3, developed in chapter 4 of the course, to write a predicate to construct a binary search tree from a list of integer number
λ> construct [3, 2, 5, 7, 1]
Branch 3 (Branch 2 (Branch 1 Empty Empty) Empty) (Branch 5 Empty (Branch 7 Empty Empty))
λ> symmetric . construct $ [5, 3, 18, 1, 4, 12, 21]
True
λ> symmetric . construct $ [3, 2, 5, 7, 1]
True
add :: Ord a => a -> Tree a -> Tree a
add x Empty = Branch x Empty Empty
add x t@(Branch y l r) = case compare x y of
LT -> Branch y (add x l) r
GT -> Branch y l (add x r)
EQ -> t
construct xs = foldl (flip add) Empty xs
思路:
总结下来,construct这种事情需要一个一个add,然后从上往下比较,这个就是BST的insert node 的过程。
flip 交换顺序. add empty x -----> add x empty
case compare x y of 相当于switch case