树:广度优先遍历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/
 * 

* 3 * / \ * 9 20 * / \ * 15 7 *

* [3 9 20 15 7] *

* 知识点扫盲 * 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 levelOrder(TreeNode root) { List result = new ArrayList<>(); if (root == null) { return result; } Queue 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; } }

  

你可能感兴趣的:(树:广度优先遍历1)