How to create a linked list of nodes that are contained in the max-Depth of a Binary Tree using Java

ⅰ亾dé卋堺 提交于 2019-12-13 04:46:15

问题


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:

  1. start at the root of the binary tree
  2. use a breadth-first or depth-first search to reach leaf nodes (nodes which do not have any children nodes)
    1. when you reach a leaf node, check it's depth:
      1. if it's not equal to the max depth, ignore it and continue with the search
      2. 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
  3. add this leaf node to the linked list, then go to it's parent
  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!