zoukankan      html  css  js  c++  java
  • 树:广度优先遍历1

    package club.interview.tree;
    
    import club.interview.tree.base.TreeNode;
    
    import java.util.ArrayList;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Queue;
    
    /**
     * 从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
     * fixme https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/
     * <p>
     * 3
     * / 
     * 9  20
     * /  
     * 15   7
     * <p>
     * [3 9 20 15 7]
     * <p>
     * 知识点扫盲
     * 1. LinkedList是Queue的实现类
     * 2. 出队入队的操作分别是 poll,offer
     *
     * @author QuCheng on 2020/6/3.
     */
    public class BFSTree {
    
        private TreeNode buildNode() {
            TreeNode t1 = new TreeNode(15);
            TreeNode t2 = new TreeNode(7);
            TreeNode t3 = new TreeNode(20, t1, t2);
            TreeNode t4 = new TreeNode(9);
            return new TreeNode(3, t4, t3);
        }
    
        public static void main(String[] args) {
            BFSTree b = new BFSTree();
            System.out.println(b.levelOrder(b.buildNode()));
        }
    
        /**
         * 列用队列FIFO的特性,遍历左右节点放入队列中,然后按层输出
         */
        public List<Integer> levelOrder(TreeNode root) {
            List<Integer> result = new ArrayList<>();
            if (root == null) {
                return result;
            }
            Queue<TreeNode> temp = new LinkedList<>();
            temp.offer(root);
            while (!temp.isEmpty()) {
                TreeNode treeNode = temp.poll();
                result.add(treeNode.val);
                if (treeNode.left != null) {
                    temp.offer(treeNode.left);
                }
                if (treeNode.right != null) {
                    temp.offer(treeNode.right);
                }
            }
            return result;
        }
    }
    

      

  • 相关阅读:
    Centos7LDAP LDAPadmin的完整部署记录(改良版,其它文档太多坑)
    linux weblogic11g 部署
    redis离线集群安装
    Weblogic11g 10.3部署
    jdk安装部署
    tar.xz文件如何解压
    linux-Centos7安装python3并与python2共存
    ssh免密码登录配置方法
    Docker容器安装weblogic详细教程
    linux命令分块总结---多操作才是真理
  • 原文地址:https://www.cnblogs.com/nightOfStreet/p/13039876.html
Copyright © 2011-2022 走看看