題目地址:
https://leetcode-cn.com/probl…
題目描述:
給定一個二叉樹,返回其節點值的鋸齒形層次遍歷。(即先從左往右,再從右往左進行下一層遍歷,以此類推,層與層之間交替進行)。
解答:
二叉樹的層序遍歷,只不過對於偶數層來說,把該層的遍歷結果轉置一下就行了。
java ac程式碼:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> ans = new ArrayList(100);
ArrayDeque<TreeNode> deque = new ArrayDeque(1000);
if(root == null)return ans;
deque.offer(root);
int num = 1;
while(!deque.isEmpty())
{
int n = deque.size();
List<Integer> temp = new ArrayList(n);
for(int i = 0;i < n;i++)
{
TreeNode node = deque.poll();
temp.add(node.val);
if(node.left != null)deque.offer(node.left);
if(node.right != null)deque.offer(node.right);
}
if((num&1) != 1)
Collections.reverse(temp);
ans.add(temp);
num++;
}
return ans;
}
}