相关疑难解决方法(0)

遍历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;
    }
}
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)

java binary-tree traversal tree-traversal

15
推荐指数
2
解决办法
6万
查看次数

标签 统计

binary-tree ×1

java ×1

traversal ×1

tree-traversal ×1