programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Subtree/Child of an tree

Terence hiu
Ranch Hand
Posts: 36
• 1
Hi,

I would like to create a method that returns the sub tree of a tree. Say i have a method that accepts a int parameter. The parameter is the nth node. I would like to return that particular node which is a reference.
If my input parameter was 5 then, it will return the 5th node. That is the reference of the 5th node that contains node 6 and node 7.
(1)
/\
(2) (5)
/\ /\
(3)(4) (6)(7)

Bellow is my node class.

Campbell Ritchie
Marshal
Posts: 56598
172
What is your definition of 5th node? The diagram does not help. Knowing the definition of 5th node will allow you easily to write the algorithm.

Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
just do any one of the tree traversal, when you on a node compare the node's data/value with input parameter .
if both are equal return the current node which is going to root node of your sub tree.

Terence hiu
Ranch Hand
Posts: 36
Campbell Ritchie wrote:What is your definition of 5th node? The diagram does not help. Knowing the definition of 5th node will allow you easily to write the algorithm.

That 5th node can be the 5th node detected by postorder

Terence hiu
Ranch Hand
Posts: 36
Seetharaman Venkatasamy wrote:just do any one of the tree traversal, when you on a node compare the node's data/value with input parameter .
if both are equal return the current node which is going to root node of your sub tree.

The inpute parameter is not the node to search, it is the nth node i would like to return

Jayesh A Lalwani
Rancher
Posts: 2762
32
When you say nth node, what does it mean? the Nth node that is added into the tree? The Nth node according to some sorting order? The Nth node when you do a depth first walk? The Nth node when you do a breadth first walk?

Terence hiu
Ranch Hand
Posts: 36
The Nth node when you do a breadth first walk.

 It is sorta covered in the JavaRanch Style Guide.