I have got a binary tree
public class Node
{
int value;
Node left;
Node right;
public Node getLeft() {
return left;
}
public Node getRight() {
return right;
}
public String getValue() {
return value;
}
}
And in main I have got a function to traverse it. For tree
5
/ \
3 7
/ \
1 2
First one creates a queue of nodes with breadth first traversal(5,3,7,1,2). Second one returns value of a node for eg. 7 for number 2 or 2 for number 4.
private void queueOfTreaversed() {
LinkedList<Node> queue = new LinkedList<Node>();
if (root != null)
queue.add(root);
while (!queue.isEmpty()) {
Node temp = queue.removeFirst();
if (temp.getLeft() != null && temp.getRight() != null) {
traversed.add(temp); //there is a difference
queue.add(temp.getLeft());
queue.add(temp.getRight());
}
}
}
public int getValue(int n) {
LinkedList<Node> queue = new LinkedList<Node>();
if (root != null)
queue.add(root);
while (!queue.isEmpty() && n>0) {
Node temp = queue.removeFirst();
if (temp.getLeft() != null && temp.getRight() != null) {
queue.add(temp.getLeft());
queue.add(temp.getRight());
}
}
return queue.peekFirst().getValue(); //there is a difference
}
And I have got duplication of code that I do not how to get rid off. I use traversed in meantime and pop elements from this queue so elements will not be in this order and traversed cannot be used. Could anyone give any hint?
答案 0 :(得分:2)
Once you have got the traversed nodes in traversed
, your getValue(int n)
function can actually index into traversed
to get the value you want. In your getValue(int n)
function, just use code like this:
if (n < traversed.size()) {
return traversed.get(n).getValue();
}
throw new Exception("Element not existed");
To be able to use traversed
, just return it in your queueOfTreaversed
function.