leetcode103二叉树的锯齿形层序遍历
Posted lisin-lee-cooper
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode103二叉树的锯齿形层序遍历相关的知识,希望对你有一定的参考价值。
一.问题描述
给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
返回锯齿形层序遍历如下:
[
[3],
[20,9],
[15,7]
]
二.示例代码
public class ZLevelBinarySearchTree103 {
public static void main(String[] args) {
TreeNode root = new TreeNode(5);
TreeNode node1 = new TreeNode(1);
TreeNode node2 = new TreeNode(9);
TreeNode node3 = new TreeNode(7);
TreeNode node4 = new TreeNode(10);
root.left = node1;
root.right = node2;
node2.left = node3;
node2.right = node4;
List<List<Integer>> result = zLevelOrder(root);
System.out.println(result);
}
private static List<List<Integer>> zLevelOrder(TreeNode root) {
List<List<Integer>> ans = new LinkedList<>();
if (root == null) {
return ans;
}
Queue<TreeNode> nodeQueue = new LinkedList<>();
nodeQueue.offer(root);
boolean isOrderLeft = true;
while (!nodeQueue.isEmpty()) {
Deque<Integer> levelList = new LinkedList<>();
int size = nodeQueue.size();
for (int i = 0; i < size; ++i) {
TreeNode curNode = nodeQueue.poll();
if (isOrderLeft) {
levelList.offerLast(curNode.val);
} else {
levelList.offerFirst(curNode.val);
}
if (curNode.left != null) {
nodeQueue.offer(curNode.left);
}
if (curNode.right != null) {
nodeQueue.offer(curNode.right);
}
}
ans.add(new LinkedList<>(levelList));
isOrderLeft = !isOrderLeft;
}
return ans;
}
}
以上是关于leetcode103二叉树的锯齿形层序遍历的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode Algorithm 103. 二叉树的锯齿形层序遍历