inorder

Rebuild a binary tree from preorder and inorder lists

亡梦爱人 提交于 2019-12-02 06:44:25
Hi I'm trying to rebuild a binary tree, I almost got it, except it throws me an error and I don't know why buildTree :: (Ord a, Eq a) => [a] -> [a] -> Tree a buildTree [] [] = Empty buildTree preOrd inOrd = Node root left right where root = head preOrd left = buildTree leftPreOrd leftInOrd right = buildTree rigthPreOrd leftInOrd Just rootInd = elemIndex root inOrd leftPreOrd = tail (take (rootInd + 1) preOrd) rigthPreOrd = tail (drop rootInd preOrd) leftInOrd = take rootInd inOrd rightInord = drop (rootInd + 1) inOrd When I call it using buildTree [10,5,2,6,14,12,15] [2,5,6,10,12,14,15] it

Can this implementation of in-order traversal of a binary tree be improved?

给你一囗甜甜゛ 提交于 2019-12-02 05:37:28
问题 I wrote a straightforward in-order-traversal function ( toList1 ) for a binary tree. However, I worry about its complexity (memory / time). Is there a better way to implement it? data Tree a = Empty | Node a (Tree a) (Tree a) toList1 :: (Tree a) -> [a] toList1 Empty = [] toList1 (Node x lx rx) = (toList lx) ++ [x] ++ (toList rx) 回答1: Haskell's append ++ performs linearly in the length of its left argument, which means that you may get quadratic performance if the tree leans left . One

How does this inorder traversal algorithm work?

早过忘川 提交于 2019-12-01 05:06:03
问题 I don't have much experience with recursion, so I'm having a hard time determining exactly how this algorithm works: public static void inorder(Node<?> n) { if (n != null) { inorder(n.getLeft()); System.out.print(n.data + " "); inorder(n.getRight()); } } I know that it visits the left and right child nodes of every node in the tree, but I just can't get my head around why exactly it works. 回答1: I'll try to give it a shot. Imagine a tree a b c d e f g Each letter represents a Node object. What