Java 用循环代替递归遍历二叉搜索树
有人知道如何使用循环而不是递归遍历二叉搜索树吗 我有递归方法Java 用循环代替递归遍历二叉搜索树,java,tree,binary-tree,binary-search-tree,tree-traversal,Java,Tree,Binary Tree,Binary Search Tree,Tree Traversal,有人知道如何使用循环而不是递归遍历二叉搜索树吗 我有递归方法 public static int countMatches(BinaryNodeInterface<Integer> tree, Integer key) { int matches = 0; if (tree != null) { if (tree.getData().equals(key)) matches++; matches += c
public static int countMatches(BinaryNodeInterface<Integer> tree, Integer key)
{
int matches = 0;
if (tree != null)
{
if (tree.getData().equals(key))
matches++;
matches += countMatches(tree.getLeftChild(), key);
matches += countMatches(tree.getRightChild(), key);
}
return matches;
}
public static int countMatches(二进制节点接口树,整数键)
{
int匹配=0;
如果(树!=null)
{
if(tree.getData().equals(key))
匹配++;
matches+=countMatches(tree.getLeftChild(),key);
matches+=countMatches(tree.getRightChild(),key);
}
返回比赛;
}
您可以使用队列执行级别顺序遍历
public static int countMatches(BinaryNodeInterface<Integer> tree, Integer key)
{
int matches = 0;
if (tree == null) return 0;
Queue<BinaryTreeNodeInterface<Integer>> queue = new LinkedList<BinaryTreeNodeInterface<Integer>>();
queue.add(tree);
while (!queue.isEmpty()) {
BinaryTreeNodeInterface<Integer> current = queue.remove();
if (current.getData().equals(key))
matches++;
if (current.getLeftChild() != null)
queue.add(current.getLeftChild());
if (current.getRightChild() != null)
queue.add(current.getRightChild());
}
return matches;
}
public static int countMatches(二进制节点接口树,整数键)
{
int匹配=0;
if(tree==null)返回0;
Queue Queue=new LinkedList();
添加(树);
而(!queue.isEmpty()){
BinaryTreeNodeInterface current=queue.remove();
if(current.getData().equals(key))
匹配++;
if(current.getLeftChild()!=null)
add(current.getLeftChild());
if(current.getRightChild()!=null)
add(current.getRightChild());
}
返回比赛;
}
一个简单的方法是使用一个贯穿其中的列表,或者是宽度优先
public static int countMatches(BinaryNodeInterface<Integer> tree, Integer key)
{
ArrayList<Node> open = new ArrayList<Node>();
open.add(tree.getRoot());
int matches = 0;
while(!open.isEmpty())
{
if(open.get(0).hasLeft())
open.add(open.get(0).getLeftChild());
if(open.get(0).hasRight())
open.add(open.get(0).getRightChild());
if(open.get(0).equals(key))
++matches;
open.remove(0);
}
return matches;
}
public static int countMatches(二进制节点接口树,整数键)
{
ArrayList open=新建ArrayList();
open.add(tree.getRoot());
int匹配=0;
而(!open.isEmpty())
{
if(open.get(0.hasLeft())
open.add(open.get(0.getLeftChild());
if(open.get(0.hasRight())
open.add(open.get(0.getRightChild());
if(open.get(0).equals(key))
++火柴;
打开。移除(0);
}
返回比赛;
}
这可能不是最有效的方法,但它应该符合你的要求。
这是一个深度优先的方法,但如果需要,将其更改为广度优先应该不会太难。请缩进您的代码。在它缩进之前我不能看…是的,我知道。你也弄明白了吗?实际上Eric的可能是更好的选择,因为在数组列表上使用Que可能更容易组织