假设我有一个简单的二叉树节点类,如下所示:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我如何添加一个能够以递归方式遍历任何大小树的方法,从左到右访问每个现有节点,而无需重新访问已遍历的节点?
这会有用吗?:
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) …Run Code Online (Sandbox Code Playgroud)