假设我有一个简单的二叉树节点类,如下所示:
public class BinaryTreeNode {
public String identifier = "";
public BinaryTreeNode parent = null;
public BinaryTreeNode left = null;
public BinaryTreeNode right = null;
public BinaryTreeNode(BinaryTreeNode parent, String identifier)
{
this.parent = parent; //passing null makes this the root node
this.identifier = identifier;
}
public boolean IsRoot() {
return parent == null;
}
}
我将如何添加一种能够递归遍历任何大小的树的方法,从左到右访问每个现有节点,而无需重新访问已经遍历过的节点?
这会工作吗?:
public void traverseFrom(BinaryTreeNode rootNode)
{
/* insert code dealing with this node here */
if(rootNode.left != null)
rootNode.left.traverseFrom(rootNode.left);
if(rootNode.right != null)
rootNode.traverseFrom(rootNode.right);
}