在 Java 中遍历二叉树的所有节点
2022-09-02 11:44:28
假设我有一个简单的二叉树节点类,如下所示:
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);
}