【发布时间】:2011-09-08 07:16:58
【问题描述】:
我不知道如何递归地遍历给定的二叉树,只需使用树的以下方法。例如,每个 TreeNode 都有一个 int Value 和一个 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();
【问题讨论】:
-
我建议看一些数据结构的书。坦南鲍姆怎么样?
-
家庭作业或多或少 - 我通过创建树的顺序列表并遍历每个节点来解决这个问题。不幸的是,我们必须使用递归方法。
标签: java recursion tree binary-tree