比方說,我有一個簡單的二進制樹節點類,如下所示:遍歷通過二進制樹的所有節點在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