題目
給定一個二叉樹,返回其節點值的鋸齒形層次遍歷。(即先從左往右,再從右往左進行下一層遍歷,以此類推,層與層之間交替進行)。
例如:
給定二叉樹 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回鋸齒形層次遍歷如下:
[
[3],
[20,9],
[15,7]
]
題解
這道題要求用z字型,就是要求知道深度。因爲知道深度我們就可以根據深度的奇偶來判斷如何打印。
首先相到的就是層序遍歷,然後記錄是第幾層。層序遍歷用隊列的代碼我們已經很熟悉了。
/**
* 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 LinkedList<>();
if (root == null) {
return res;
}
LinkedList<TreeNode> queue = new LinkedList<>();
queue.add(root);
int depth = 0;
while (!queue.isEmpty()) {
int size = queue.size();
LinkedList<Integer> currentRes = new LinkedList<>();
// 當前層一直出隊.
while (size > 0) {
TreeNode current = queue.poll();
TreeNode left = current.left;
TreeNode right = current.right;
if (left != null) {
queue.add(left);
}
if (right != null) {
queue.add(right);
}
// 奇數層,從頭添加; 偶數層從尾部添加.
if (depth % 2 != 0) {
currentRes.add(0, current.val);
} else {
currentRes.add(current.val);
}
size--;
}
// 把當前層遍歷的結果加入到結果中.
res.add(currentRes);
depth++;
}
return res;
}
}
同之前一樣,我們想一想有沒有遞歸的解法.
我們可以採用先序遍歷的方式,先遍歷節點,然後遞歸的遍歷左子樹和右子樹。
稍作改動的是,需要在遍歷左子樹和右子樹的時候帶上深度的信息,才能知道是加在列表頭還是列表尾部。
遞歸的結束條件就是遇到空節點。
/**
* 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 LinkedList<>();
if (root == null) {
return res;
}
helper(res, root, 0);
return res;
}
public void helper(List<List<Integer>> res,TreeNode root, int depth) {
if (root == null) {
return;
}
// 注意這裏new List, 說明當前節點遞歸進入了新的層.
if (res.size() <= depth) {
res.add(new LinkedList<>());
}
if (depth % 2 != 0) {
res.get(depth).add(0, root.val);
} else {
res.get(depth).add(root.val);
}
helper(res, root.left, depth + 1);
helper(res, root.right, depth + 1);
}
}
熱門閱讀