笔试-遍历二叉树之字形输出

笔试题:遍历二叉树之字形输出,即第一行从左到右输出,第二行从右到左输出
思路:层次遍历,记录标记
import lombok.Data;
import org.junit.Test;
import java.util.*;
public class LeeCodeTest {

    @Data
    public class Node {
        private String value;
        private Node leftChild;
        private Node rightChild;
    }


    public void trace(ArrayDeque<Node> queue, int level) {
        int size = queue.size();
        ArrayList<String> list = new ArrayList<>();

        for (int i = 0; i < size; i++) {
            Node head = queue.poll();

            if (level % 2 == 0) {
                list.add(head.value + "-");
            } else {
                list.add(0, head.value + "_");
            }
            if (head == null) {
                return;
            }
            if (head.leftChild != null) {
                queue.add(head.leftChild);
            }
            if (head.rightChild != null) {
                queue.add(head.rightChild);
            }
        }

        if (list.size() > 0) {
            System.out.println(list.toString());
        }

        if (size > 0) {
            trace(queue, level + 1);
        }
    }


    @Test
    public void testBiTreeTrace() {


        ArrayDeque<Node> queue = new ArrayDeque<>();


        Node parent = new Node();
        parent.value = "1";

        Node l1 = new Node();
        l1.value = "2";

        Node l2 = new Node();
        l2.value = "3";

        Node l3 = new Node();
        l3.value = "5";

        Node l4 = new Node();
        l4.value = "4";
        parent.leftChild = l1;
        parent.rightChild = l2;
        l2.rightChild = l3;
        l2.leftChild = l4;
        ((ArrayDeque<Node>) queue).addFirst(parent);
        trace(queue, 0);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值