二叉树-查找PostOrder遍历的N阶

时间:2018-12-06 16:15:54

标签: java binary-tree binary-search-tree tree-traversal postorder

我正在尝试找到二叉树后顺序遍历的第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个顺序。

0 个答案:

没有答案
相关问题