如何在递归中查找preOrder遍历中的下一个节点

时间:2013-12-11 20:24:13

标签: java tree preorder

我想编写一个接受树节点的函数。它应该返回在preOrder中采用的节点之后访问的下一个节点。 我写了这段代码: (此代码搜索左子项并返回它。如果temp没有左子,但它有右子,则此函数返回右项。但如果Node是一个叶子且没有子,它会获得父项,直到得到一个节点正确的孩子。)

    public Node fineNextPreOrder(Node temp)
    {
    if(temp.left!=null)
        return temp.left;
    else if((temp.left==null)&&(temp.right!=null))
        return temp.right;
    else if((temp.left==null)&&(temp.right==null))
    {
        while((temp!=root)&&(!((temp.parent.left!=null)&&(temp.parent.left==temp)&&(temp.parent.right!=null))))
            temp = temp.parent;
        if(temp != root)
            return temp.parent.right;
    }

        return null;

}

它确实有效,但我想让它递归。

任何人都可以帮我解决这个问题吗?

提前感谢您的注意。

1 个答案:

答案 0 :(得分:3)

public Node preOrderMod(Node temp)
{
    if (temp != null)
    {
        if (temp.left != null)
            return temp.left;

        if (temp.right != null)
            return temp.right;

        return mod(temp.parent);
    }

    return null;
}

private Node mod(Node temp)
{
    if (temp != null && temp != root)
    {
       if (temp.parent.left == temp && temp.parent.right != null)
          return temp.parent.right;

       return mod(temp.parent);
    }

    return null;
}

供参考:

  

预订:根左右
按顺序:左根右。
  后序:左右根

相关问题