You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
return its zigzag level order traversal as:
题目要求按照Zigzag格式存放二叉树节点值,第一行从左至右,第二行从右至左,第三行再从左至右...如此顺序。
我的第一个反应是按照102. Binary Tree Level Order Traversal的思路设置两个节点判断是否为一行的思路,层次遍历二叉树。代码如下:
还有另一种做法,充分利用Java集合的LinkedList类作为双端队列的优势,即可以头尾插入或者删除元素的特点,可以设置以下添加二叉树节点方式:如果当前行是从左至右顺序的,从队头取出节点,并把该节点的左子节点和右子节点(如果存在)插入队尾中;如果当前行是从右至左顺序的,从队尾取出节点,并把该节点的右子节点和左子节点(如果存在)插入队头中。辨别是否到一行的结尾节点方法是分别设置last和nLast节点,last指向当前行尾节点,nLast是根据每行按照Zigzag顺序的头节点的左(或右)子节点来确立的。
参考资料
The text was updated successfully, but these errors were encountered: