次のような単純なバイナリ ツリー ノード クラスがあるとします。
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);
}