比方说,我有一个简单的二进制树节点类,如下所示:遍历通过二进制树的所有节点在Java中
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);
}
看起来很像下面的正确答案。 – 2013-03-09 02:29:49
@PeterWooster - 对,除了我从每个节点调用遍历方法,导致递归发生递归为每个节点,而不是从根 – RectangleEquals 2013-03-09 03:38:04