Interview question in Java
I found this interview question in Java, and I think the output is right to left order un开发者_开发百科der number 3, means:
2 1 2 0 1
Am I right ?
thnx !!
The IntNode class:
public class IntNode;
{
private int _value;
private IntNode _next;
public IntNode (int val, IntNode n)
{
_value = val;
_next = n;
}
public IntNode getNext () {return _next;}
public void setNext (IntNode node) {_next = node;}
public int getValue () {return _value;}
public void setValue (int v) {_value = v;}
}
The IntList class:
public class IntList
{
private IntNode _head;
public IntList() {_head = null;}
public void addHead (int val)
{
_head = new IntNode (val, _head);
}
}
The Node Class:
public class Node
{
private int _number;
private Node _leftSon, _rightSon;
public Node (int number)
{
_number = number;
_leftSon = null;
_rightSon = null;
}
public int getNumber() {return _number;}
public Node getLeftSon() {return _leftSon;}
public Node getRightSon() {return _rightSon;}
}
The BinaryTree Class:
The BinaryTree Class:
public class BinaryTree
{
public static IntList what (Node root , int i)
{
IntList level = new IntList();
if (root != null)
what (level, i, root);
return level;
}
private static void what (IntList level, int i, Node t)
{
if (t != null)
{
if (i>0)
{
what (level, i-1, t.getRightSon());
what (level, i-1, t.getLeftSon());
}
else
level.addHead(t.getNumber());
}
}
}
And the question was:
1) For the following tree(pic), what will be printed on screen for the following lines:
IntList list = BinaryTree.what(root, 3);
Sys...out... (list);
2) What does the method 'what' generaly, when she receives a root of a binary tree ?
Without running the code, it looks to me like what it does is
- If it's at a level of the tree < 3, descend into the Right then Left child
- If at level 3, add the value of the current node to the list
As such, it looks like it prints out all the values of the nodes at depth 3, from right to left:
9, 1, 7, 6, 8
精彩评论