如何在Java中从右向左遍历二叉树? [英] How can i traverse a binary tree from right to left in java?
本文介绍了如何在Java中从右向左遍历二叉树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从右到左遍历二叉树,并将姓氏相同的每个项目添加到队列中.我已经正确实现了一个队列列表类和一个树节点类,但是,当我尝试查找某些东西时,我得到了一个空指针异常. (当然,我已经为二叉树写了一个插入方法).
I want to traverse a binary tree from right to left and add to a queue every item with same last name. I have correctly implement a Queue List class and a Tree Node class but, i get a null pointer exception when i try to find something. (Of course i have written an insertion method for the binary tree).
public class ST {
private TreeNode root;
private int size;
private Queue q;
public Queue searchByLastName(String last_name) {
searchByLastNameRec(this.root, last_name);
return q;
}
private void searchByLastNameRec(TreeNode newroot, String last_name) {
if (newroot == null)
return;
if (newroot.right != null) {
if (newroot.right.item.getLast_name().equalsIgnoreCase(last_name)) {
q.put(newroot.right.item);
}
searchByLastNameRec(newroot.right, last_name);
}
if (newroot.left != null) {
if (newroot.left.item.getLast_name().equalsIgnoreCase(last_name)) {
q.put(newroot.left.item);
}
searchByLastNameRec(newroot.left, last_name);
}
}
public class TreeNode {
Suspect item;
TreeNode left, right, parent;
int N;
public TreeNode(Suspect item) {
if (item == null)
throw new IllegalArgumentException();
this.item = item;
}
}
推荐答案
尝试一下
private void searchByLastNameRec(TreeNode newroot, String last_name) {
if (newroot == null || newroot.item == null)
return;
if (Objects.equals(last_name, newroot.item.getLast_name()))
q.put(newroot.item);
searchByLastNameRec(newroot.right, last_name);
searchByLastNameRec(newroot.left, last_name);
}
这篇关于如何在Java中从右向左遍历二叉树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文