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;

}

}

解决方案

Try this

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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值