二叉树 - 如何在没有任何参数的情况下遍历递归

时间:2011-06-04 08:27:51

标签: java recursion tree binary-tree

我不知道如何递归遍历给定的二叉树,只需使用树的以下方法。例如,每个TreeNode都有一个int值和一个getter TreeNode.getValue(),现在我想找到树中具有最大值的节点。请注意,树只有一个指向其currentNode的指针,您可以移动到父节点,右节点,左节点或根节点。

我的问题:

Tree tree;

public int findMaxValue() {
    //how to implement this as recursive function
}

树类:

/**
 * The abstract class for a tree.
 * @author JK, KM
 */
public abstract class Tree {

    /**
     * Moves to the left child of the current node
     * 
     * @return true if left child exists and the move was successful; otherwise
     *         false
     */
    public abstract boolean moveToLeftNode();

    /**
     * Moves to the right child of the current node
     * 
     * @return true if right child exists and the move was successful; otherwise
     *         false
     */
    public abstract boolean moveToRightNode();

    /**
     * Moves to the parent of the current node
     * 
     * @return true if parent exists and the move was successful; otherwise
     *         false
     */
    public abstract boolean moveToParentNode();

    /**
     * @return true if left child exists; otherwise false
     */
    public abstract boolean hasLeftNode();

    /**
     * @return true if right child exists; otherwise false
     */
    public abstract boolean hasRightNode();

    /**
     * @return true if parent exists; otherwise false
     */
    public abstract boolean hasParentNode();

    /**
     * Sets the left child of the current node
     * 
     * @return true if successful; otherwise false (no root set)
     * 
     */
    public abstract boolean setLeftNode(TreeNode node);

    /**
     * Sets the right child of the current node
     * 
     * @return true if successful; otherwise false (no root set)
     * 
     */
    public abstract boolean setRightNode(TreeNode node);

    /**
     * Sets the current node. If the tree is empty, sets the root.
     * 
     */
    public abstract void setCurrentNode(TreeNode node);

    /**
     * @return the current node or null if the tree is empty
     */
    public abstract TreeNode getCurrentNode();

    /**
     * moves to the root node of this tree
     * 
     * @return true if there's a root; otherwise false
     */
    public abstract boolean moveToRoot();

    /**
     * clears the whole tree, which includes deleting all nodes and the root
     * node
     */
    public abstract void clearTree();

1 个答案:

答案 0 :(得分:2)

您可以递归遍历二叉树,如下所示:

public int findMaxValue() {
    return max(this.node.getValue(),
               this.getLeftChild().findMaxValue(),
               this.getRightChild().findMaxValue());
}

实现这个给定的Tree接口并检查叶节点是一个练习。