Re: [闲聊] 每日LeetCode

楼主: idiont (supertroller)   2023-02-19 13:28:32
103. Binary Tree Zigzag Level Order Traversal
给一棵二元树,
求他的 zigzag level order traversal,
也就是第一层从左到右,第二层从右到左,第三层从左到右,以此类推。
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[20,9],[15,7]]
Explanation:
https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg
第一层从左到右得到 [3]
第二层从右到左得到 [20,9]
第三层从左到右得到 [15,7]
Example 2:
Input: root = [1]
Output: [[1]]
Explanation:
第一层从左到右得到[1]
Example 3:
Input: root = []
Output: []
Explanation:
没有任何节点
解题思路:
一层一层从左到右做BFS,把该层节点的值存成阵列,
如果该层是偶数层就先把阵列反转再存入答案之中。
C++ code:
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> ans;
queue<TreeNode*> que;
que.push(root);
bool left_to_right = true;
while(que.size() > 0){
vector<int> v;
int T = que.size();
while(T
作者: a9486l (a9486l)   2023-02-19 14:14:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com