Я пытаюсь найти N-й порядок обхода после заказа двоичного дерева.Дается двоичное дерево, а дается N, мне просто нужно реализовать код, чтобы найти N-й порядок.
Я просмотрел множество примеров и приблизился к поиску правильного решения,за исключением того, что ответ, кажется, несколько узлов, и я не совсем уверен, почему.
Это то, что у меня есть в настоящее время:
TreeMap<Integer, Node<T>> nodes = new TreeMap<Integer, Node<T>>();
int count = 0;
public void postOrder(Node<T> r) {
if(r == null) return;
postOrder(r.left);
postOrder(r.right);
nodes.put(count = count + 1, r);
}
/**
* Return the kth indexed element according to the Comparable sorted order of
* the tree. The leftmost node has index 0 and the rightmost node has index
* size() - 1.
*
* @param k
* index
* @return element, or null if k is out of range.
*/
public T findByOrder(int k) {
count = 0;
if(k < 0 || k > root.size() - 1) return null; // Are we out of bounds?
postOrder(root);
System.out.println(nodes.get(k).data);
return null; // Temporary return placeholder
}
Я использовал алгоритм, который я нашел, чтобы бытьнаиболее часто используется счетчик и TreeMap, чтобы найти N-й порядок.