问题
I've already created the Binary Tree and Linked list classes, I'm just in need of an algorithm that prints ONLY the nodes of the largest path. The height and size of the Binary Tree are already stored in the root node, but my problem is traversing only the largest path while adding each node to my linked list.
回答1:
I assume your binary tree nodes have a reference to their parent, is that right? Then you could use either a breadth-first search or a depth-first search and find root nodes where the depth is equal to the max depth. Once you find one such node, then from there go up the trail of parent nodes, and add each node along the way to your linked list. When you reach the top, then the linked list has all the nodes of the largest path.
This algorithm would look like this:
- start at the root of the binary tree
- use a breadth-first or depth-first search to reach leaf nodes (nodes which do not have any children nodes)
- when you reach a leaf node, check it's depth:
- if it's not equal to the max depth, ignore it and continue with the search
- if it's equal to the max depth, then you've found the end node of a largest path (there could be more than one but it doesn't seem important to distinguish them at this point). go to the next step
- when you reach a leaf node, check it's depth:
- add this leaf node to the linked list, then go to it's parent
- repeat that last step until you reach the root node and there is no parent - then your linked list has all the nodes of a longest path.
Note that the order of the nodes is from the leaf node to the root - if you need to reverse it, you can do so after the last step.
回答2:
Well make a binary tree data structure, fill it with some dummy data, traverse the tree with a depth or breadth first search and construct a linked list of the nodes in the longest path.
There's plenty of pseudo code and further information online:
http://en.wikipedia.org/wiki/Binary_tree
http://en.wikipedia.org/wiki/Linked_list
http://en.wikipedia.org/wiki/Breadth-first_search
http://en.wikipedia.org/wiki/Depth-first_search
I assume you already understand Java and are not starting completely from scratch?
If you're struggling with Java then Objects First with Java is a great book and also Introduction to Algorithms seems to be the standard book on algorithms and may be well worth looking at.
来源:https://stackoverflow.com/questions/1664390/how-to-create-a-linked-list-of-nodes-that-are-contained-in-the-max-depth-of-a-bi