如何编写代码以查找特定节点。具体来说,当我检查节点后,该怎么说呢?
public Iterator<T> pathToRoot(T targetElement, BinaryTreeNode<T> current)
throws ElementNotFoundException
{
Stack<BinaryTreeNode<T>> myStack = new Stack<>();
if (current == null)
return null;
if (current.element.equals(targetElement)) //found it
{
myStack.push(current); //adds the current element to the stack
}
// mark as visited
//mark node also as found
// return the found element
if (current.hasLeftChild() || current.hasRightChild()) //if the current node has a left or right child
{
// mark node as visited
}
if (current.hasLeftChild())//if the current node has a left child node
pathToRoot(targetElement, current.getLeft()); // check the left child node
if (current.hasRightChild())//same thing as above but for the right
pathToRoot(targetElement, current.getRight());
if(current != targetElement && /*node has been visited*/)
myStack.pop(); // pop node from the stack
return myStack.toString(); //return string of path to root
}
/ 使用dfs搜索来找到节点 /
答案 0 :(得分:1)
将图节点标记为已访问的唯一目的是确保您不会陷入无限循环,因为图可以包含一个循环。
二叉树是一种特殊的图形,它不包含循环,因此遍历时无需将节点标记为已访问。
此外,通常以如下方式对二叉树进行排序:当前节点包含值X,其左子树具有值小于X的节点,其右子树具有值大于X的节点。这样一来,搜索就需要对数时间,在您演示的代码中,您似乎并没有利用它。
因此,我认为您对二叉树的工作原理没有很好的了解,因此在实施此功能之前,您应该进行更多研究。