Trees
- A tree is a collection of zero or more nodes.
- If any nodes exist, one special node called the root and zero and all other nodes are in subtrees of the root.
- A forest is a collection of rooted trees.
- A more generic definition of a tree is a acyclic graph. This
- This is a non-rooted tree
- Or a free tree.
- We generally deal with this definition as a graph.
- Trees are used everywhere
- To organize files (file system, operating systems)
- Evaluate expressions , compilers, languages
- Adjacent nodes have a parent-child relationship.
- A node with no parents is the root.
- A node no children is called a leaf
- Ancestors are above a node in a tree
- Descendants are below a given node
- The depth of a node is the length of the path from the node to the root.
- This is a per node property
- Which can change
- The root is of depth 0
- The height of a tree is the length of the longest path from a node to the root.
- This is a per tree property
- It can change as well.
- We further restrict trees by forcing them to meet given conditions or properties.
- A binary tree is a tree where each node has at most two children.
- A binary search tree is a binary tree where all of the values stored in nodes in the left subtree of a node are less than (or equal to) the values stored in the node and all of the values stored in the nodes of the right subtree are greater than the values stored in the node.
- An AVL tree is a binary search tree with the AVL property: For every node in a tree, the height of the left and right subtrees can differ by at most one.
- Some tree algorithms:
- Tree height
-
HEIGHT(T)
- ifT=&Null;
- return -1
- else
- return max(HEIGHT(Tleft),HEIGHT(Tright))+1
- Why the -1 on line 1?
- Terminate?
- Right?
- Time?
- Notice, that line 1 gets called for more than the number of nodes in the tree.
- He observes, that it is called n+1 times on empty nodes, (if there are n nodes in the tree).
- Could we prove this?
- So we will call the routine n times on the n nodes in the tree, and n+1 times on the "empty" nodes.
- Tree Traversals
- Visit every node in the tree
- preorder traversal
- Visit the root node
- Visit the left subtree
- Visit the right subtree
- inorder traversal
- Visit the left subtree
- Visit the root node
- Visit the right subtree
- postorder traversal
- Visit the left subtree
- Visit the right subtree
- Visit the root node
- Insertion
- This is tricky, and depends on tree type.
- How would we insert into a binary search tree?