BFS二叉树

题目

https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof

解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public int[] levelOrder(TreeNode root) {
if (root == null) return new int[0];

Queue<TreeNode> queue = new LinkedList<TreeNode>(){{ add(root); }};
ArrayList<Integer> ans = new ArrayList<>();
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
ans.add(node.val);
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
int[] res = new int[ans.size()];
for (int i=0; i<ans.size(); i++) {
res[i] = ans.get(i);
}
return res;
}
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×