Class Path<T>
- Type Parameters:
T- The type of value store in theTreeNode
Path represents a one-way path between two TreeNodes in a binary tree.
The Path can be root-to-leaf or node-to-node. The internal of Path is a doubly linked list, with each
list node wrapping a TreeNode as list node value.
Path is designed for enhancing the performance of
path-traversing algorithm. For example, we can cut a
Path in the middle using trim(TreeNode) in constant time, instead of iteratively removing path
tails(O(n) time). In the meantime, we can also get the length of the Path in constant time.
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidAppends aTreeNodeto the end of this path.static <T> Path<T> deepCopyOf(Path<T> other) static <T> Path<T> getLast()Returns the tail of this path.booleanisEmpty()Returns whether there are anyTreeNodealready been added to the path yet.intlength()Returns the length of this path.Deletes the tail of this path.toString()voidKeeps removingTreeNodeelements from end of an under-construction path (last, 2nd last, 3rd last ...) until the element to be removed equals to a specified element.view()Returns an immutable view of all path elements in thisPathat the time of calling this method.
-
Constructor Details
-
Path
public Path()
-
-
Method Details
-
emptyPath
-
deepCopyOf
Constructs aPathcontaining the path elements of the specifiedPath, in the order they are contained in the specifiedPath.- Type Parameters:
T- The type of value store in theTreeNode- Parameters:
other- ThePathwhose path elements are to be placed into the newPath- Returns:
- a new
Pathinstance - Throws:
NullPointerException- if theotherisnull
-
view
Returns an immutable view of all path elements in thisPathat the time of calling this method.Adding or removing elements in either the view or the original
Pathis not reflected on the other side. In other words, since a binary tree is immutable(becauseTreeNodeis immutable), mutating the tree(or a path of it) must result in a new view.Generating the view takes O(n) time where n is the length of the list.
- Returns:
- a
Listof current path elements of a binary tree path
-
trim
Keeps removingTreeNodeelements from end of an under-construction path (last, 2nd last, 3rd last ...) until the element to be removed equals to a specified element.Path is assumed not to be empty.
This method executes in constant time.
- Parameters:
expectedTail- The specified element that signals the stop of the trimming process
-
addLast
-
getLast
Returns the tail of this path.- Returns:
- a
TreeNodereference - Throws:
NoSuchElementException- if the path isempty
-
isEmpty
public boolean isEmpty()Returns whether there are anyTreeNodealready been added to the path yet.- Returns:
trueis path is empty orfalse, otherwise
-
removeLast
Deletes the tail of this path.- Returns:
- the
elementthat has been removed from this path - Throws:
NoSuchElementException- if the path isempty
-
length
-
toString
-