트리: 우선 폭 1

1576 단어
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; } }


좋은 웹페이지 즐겨찾기