Rooted Tree Recursive definition. A tree consists of a distinguished node r, called the root, and zero or more nonempty (sub)trees T 1, T 2, …, T k, each of whose roots are connected by a directed edge from r. Parent and child. The root r is the parent of each subtree root.
Tree Definition of leaves? Which nodes are leaves? Definition of siblings? Which nodes are siblings? Grandparent and grandchild?
Path and Length A path from node n 1 to node n k is defined as a sequence of nodes n 1, n 2, …, n k such that n i is the parent of n i+1, for 1≤i<k. The length of this path is the # of edges on the path, namely k-1. Is there a path of length zero? There is exactly one path from the root to each node.
Depth and Height The depth of node n i is the length of the unique path from the root to n i. What is the depth of the root? The height of n i is the length of the longest path from n i to a leaf. What is the height of a leaf? The height of a tree is equal to the height of its root. The depth of a tree is equal to the depth of the deepest leaf. How is the height of a tree related to its depth?
Ancestor and Descendant If there is a path from n i to n k, then n i is an ancestor of n k and n k is a descendant of n i. If n i ≠ n k, then n i is a proper ancestor of n k and n k is a proper descendant of n i.
Implementation of Trees Can you suggest an obvious way to implement a tree? Have in each node, besides its data, a link to each child of the node. Why is this approach possibly very inefficient? The # of children per node may vary greatly and is not known in advance. Is there a better solution?
Time Analysis Line 1 is executed exactly once per node, since each name is output once. It follows that line 2 must also be executed once per node. Line 4 can be executed at most once for each child of each node. But the number of children is exactly one less than the number of nodes. The “for” loop iterates once per iteration of line 4, plus each time the loop ends. Thus, if there are N file names to be output, then the running time is O(N).
Traversal Strategy What is the traversal strategy? In preorder traversal, work in a node is performed before (pre) its children are processed.
Size of Each Directory Suppose we know the number of disk blocks taken by each file. How can we find the size of each directory?
Postorder Traversal In a postorder traversal, the work at a node is performed after (post) its children are evaluated.