- 二叉樹的鋸齒形層次遍歷
給定一個二叉樹,返回其節點值的鋸齒形層次遍歷。(即先從左往右,再從右往左進行下一層遍歷,以此類推,層與層之間交替進行)。
思路1:BFS
思路2:DFS
/**
* 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>> res = new ArrayList<>();
if(root == null) return res;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
//mark LineNo
int depth = 0 ;
while(!queue.isEmpty()){
List<Integer> list = new ArrayList<>();
int size =queue.size();
for(int i = 0;i <size;i++){
TreeNode node =queue.poll();
if((depth & 1) == 0)
list.add(node.val);
else
list.add(0,node.val);
if(node.left != null) queue.add(node.left);
if(node.right != null) queue.add(node.right);
}
res.add(list);
depth++;
}
return res;
}
}
思路:
1.遍歷第二層的節點的順序是從左到右,而輸出第二層節點的順序是從右到左,這正好滿足棧思想,所有用棧來第二層所有節點。
2.遍歷棧輸出第二層節點,同時還需要將第三層的節點按照從右到左的順序存儲。但是不能將第三層的節點存儲到這個棧中,因爲會打亂第二層節點的順序,此時我們可以想到創建另一個棧來存儲第三層的元素。這樣層與層之間就不會產生干擾。
3.交替使用這兩個棧遍歷所有的層。
思路:
1.遍歷第二層的節點的順序是從左到右,而輸出第二層節點的順序是從右到左,這正好滿足棧思想,所有用棧來第二層所有節點。
2.遍歷棧輸出第二層節點,同時還需要將第三層的節點按照從右到左的順序存儲。但是不能將第三層的節點存儲到這個棧中,因爲會打亂第二層節點的順序,此時我們可以想到創建另一個棧來存儲第三層的元素。這樣層與層之間就不會產生干擾。
3.交替使用這兩個棧遍歷所有的層。
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> list = new ArrayList<>();
if (root == null) {
return list;
}
//棧1來存儲右節點到左節點的順序
Stack<TreeNode> stack1 = new Stack<>();
//棧2來存儲左節點到右節點的順序
Stack<TreeNode> stack2 = new Stack<>();
//根節點入棧
stack1.push(root);
//每次循環中,都是一個棧爲空,一個棧不爲空,結束的條件兩個都爲空
while (!stack1.isEmpty() || !stack2.isEmpty()) {
List<Integer> subList = new ArrayList<>(); // 存儲這一個層的數據
TreeNode cur = null;
if (!stack1.isEmpty()) { //棧1不爲空,則棧2此時爲空,需要用棧2來存儲從下一層從左到右的順序
while (!stack1.isEmpty()) { //遍歷棧1中所有元素,即當前層的所有元素
cur = stack1.pop();
subList.add(cur.val); //存儲當前層所有元素
if (cur.left != null) { //左節點不爲空加入下一層
stack2.push(cur.left);
}
if (cur.right != null) { //右節點不爲空加入下一層
stack2.push(cur.right);
}
}
list.add(subList);
}else {//棧2不爲空,則棧1此時爲空,需要用棧1來存儲從下一層從右到左的順序
while (!stack2.isEmpty()) {
cur = stack2.pop();
subList.add(cur.val);
if (cur.right != null) {//右節點不爲空加入下一層
stack1.push(cur.right);
}
if (cur.left != null) { //左節點不爲空加入下一層
stack1.push(cur.left);
}
}
list.add(subList);
}
}
return list;
}
}