LeetCode
二叉树的锯齿层序遍历
103. 二叉树的锯齿形层序遍历 - 力扣(LeetCode)
题目描述
给你二叉树的根节点 root
,返回其节点值的 锯齿形层序遍历 。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[20,9],[15,7]]
示例 2:
输入:root = [1]
输出:[[1]]
示例 3:
输入:root = []
输出:[]
提示:
- 树中节点数目在范围
[0, 2000]
内 -100 <= Node.val <= 100
思路
103. 二叉树的锯齿形层序遍历 - 力扣(LeetCode)
代码
C++
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/
class Solution {
public:vector<vector<int>> zigzagLevelOrder(TreeNode *root) {if(root == nullptr){return {};}vector<vector<int>> ans;vector<TreeNode *> cur = {root};for(bool even = false; !cur.empty(); even = !even){vector<TreeNode *> nxt;vector<int> vals;for(auto node : cur){vals.push_back(node->val);if(node->left) nxt.push_back(node->left);if(node->right) nxt.push_back(node->right);}cur = move(nxt);if(even) reverse(vals.begin(),vals.end());ans.emplace_back(vals);}return ans;}
};
Java
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public List<List<Integer>> zigzagLevelOrder(TreeNode root) {if(root == null){return List.of();}List<List<Integer>> ans = new ArrayList<>();List<TreeNode> cur = new ArrayList<>();cur.add(root);for(boolean even = false; !cur.isEmpty(); even = !even){List<TreeNode> nxt = new ArrayList<>();List<Integer> vals = new ArrayList<>(cur.size());for(TreeNode node : cur){vals.add(node.val);if(node.left != null) nxt.add(node.left);if(node.right != null) nxt.add(node.right);}cur = nxt; if(even) Collections.reverse(vals);ans.add(vals);}return ans;}
}