星尘纪云面试笔试

122 阅读1分钟
package com.liangzy.coding.ali;

import lombok.Getter;
import lombok.Setter;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 树的遍历方式
 *
 * @author :Liangzy (Potato)
 * @date: 2022-05-19 17:10
 */
public class Tree {

    private AtomicInteger count = new AtomicInteger(0);

    /**
     * 头尾节点
     */
    private Node HEAD = null;

    private Node TAIL = null;

    /**
     * 树结构的实现
     */
    @Getter
    @Setter
    public static class Node {

        /**
         * 前节点
         */
        private Node leftNode;

        /**
         * 后置节点
         */
        private Node rightNode;

        /**
         * 该节点数据
         */
        private Integer data;

        public Node(Integer data) {
            this.data = data;
        }
    }

    public int count() {
        return this.count.get();
    }

    //添加左子结点
    public static void addLeft(Node root, Node left) {
        root.setLeftNode(left);
    }

    //添加右子结点
    public static void addRight(Node root, Node right) {
        root.setRightNode(right);
    }


    /**
     * <b>树的广度优先遍历(Breadth-First-Search)</b>
     * <ol>
     *     <li></li>
     * </ol>
     */
    public void bfsFind(Node root) {
        // 先进先出
        Queue<Node> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            // 如果队列不为空
            Node tempNode = queue.poll();
            if (tempNode.getLeftNode() != null) {
                queue.offer(tempNode.getLeftNode());
            }
            if (tempNode.getRightNode() != null) {
                queue.offer(tempNode.getRightNode());
            }
        }
    }

    /**
     * <b>树的深度优先遍历(Depth-First-Search)</b>
     * <ol>
     *     <li>沿着树的深度,遍历树的节点,尽可能深的遍历树的分支</li>
     * </ol>
     */
    public void dfsFind(Node root) {
        Stack<Node> stack = new Stack<>();
        stack.push(root);
        // 如果栈不为空
        while (!stack.isEmpty()) {
            Node tempNode = stack.pop();
            System.out.println(tempNode.getData());
            if (tempNode.getRightNode() != null) {
                stack.push(tempNode.getRightNode());
            } else if (tempNode.getLeftNode() != null) {
                stack.push(tempNode.getLeftNode());
            }
        }
    }
}