横向遍历二叉树,取出值,放在链表中

二叉树正常的遍历方式又前序遍历,中序遍历,后序遍历3种,这3种遍历方式用的也最多,然而在面试过程中经常会被问到二叉树的横向遍历(又叫层次遍历),许多人不免会被问住,其实横向遍历二叉树借助队列先进先出的特性的话是很容易实现的,话不多少,先呈上代码:
首先需要先定义链表和树的结构:

public class listNode {
    protected listNode next;
    private int value;

    public listNode getNext() {
        return next;
    }

    public void setNext(listNode next) {
        this.next = next;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }
    @Override
    public String toString() {
        return "listNode{" +
                "next=" + next +
                ", value=" + value +
                '}';
    }
}
public class Tree  {
    protected Tree leftChildren;
    protected Tree rightChildren;
    protected int value;
    protected Tree parent;

    public Tree getLeftChildren() {
        return leftChildren;
    }

    public void setLeftChildren(Tree leftChildren) {
        this.leftChildren = leftChildren;
    }

    public Tree getRightChildren() {
        return rightChildren;
    }

    public void setRightChildren(Tree rightChildren) {
        this.rightChildren = rightChildren;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public Tree getParent() {
        return parent;
    }

    public void setParent(Tree parent) {
        this.parent = parent;
    }
}

接着呈上横向遍历二叉树的代码:

    public static void hengxiangBianli(Tree t){
        Queue<Tree> queue=new LinkedList<Tree>();
        listNode node=new listNode();
        Tree temp=new Tree();
        if(t!=null){
            queue.offer(t);
        }
        while (!queue.isEmpty()){
            temp=queue.poll();
            node.setValue(temp.getValue());
            node=node.next;
            if (temp.leftChildren!=null){
                queue.offer(temp.leftChildren);
            }
            if (temp.rightChildren!=null){
                queue.offer(temp.rightChildren);
            }
        }
    }

在java中Queue是一个接口,在其实现的子类中,我们选择LinkedList以多态的方式来实现队列的特性。首先判断根节点是否为空,若不为空,将根节点A入队列,之后在while循环中判断队列,若不为空,则将A出队列,并将取出的值放进链表中,之后将左子树B和右子树C都入队列,再进入新一轮的循环,之后B出队列,D,E进队列,C出队列,F,G进队列,达到的效果就是:A,B,C,D,E,F,G依次出队列并保存到链表中。
在这里插入图片描述好了,仔细理解一下,是不是特别简单呢。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值