給定一個(gè)二叉樹路呜,返回其節(jié)點(diǎn)值的鋸齒形層次遍歷。(即先從左往右轻掩,再從右往左進(jìn)行下一層遍歷幸乒,以此類推,層與層之間交替進(jìn)行)唇牧。
例如:
給定二叉樹 [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
返回鋸齒形層次遍歷如下:
[
[3],
[20,9],
[15,7]
]
鏈接:https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal
本題思路較為簡(jiǎn)單罕扎,僅為二叉樹的層序遍歷的變式聚唐,而要完成這一點(diǎn)僅需要設(shè)置一個(gè)記錄當(dāng)前層級(jí)的變量,當(dāng)其為偶數(shù)時(shí)將當(dāng)前層次遍歷結(jié)果倒置即可腔召,要達(dá)到這一點(diǎn)杆查,僅需要一個(gè)輔助數(shù)組即可。
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> ans = new ArrayList();
int count = 1;
if (root == null)
return ans;
Queue<TreeNode> docker = new LinkedList<>();
docker.offer(root);
while (docker.size() != 0) {
ArrayList<Integer> temp = new ArrayList();
int[] arr = new int[docker.size()];
int num = docker.size();
for (int i = 0; i < num; i++) {
TreeNode p=docker.poll();
arr[i] =p.val;
if (p.left != null)
docker.offer(p.left);
if (p.right != null)
docker.offer(p.right);
}
if (count % 2 == 1) {
for (int i = 0; i < arr.length; i++) {
temp.add(arr[i]);
}
} else {
for (int i = arr.length - 1; i >= 0; i--) {
temp.add(arr[i]);
}
}
count++;
ans.add(temp);
}
return ans;
}