从头做leetcode之leetcode 103 二叉树的锯齿形层次遍历

    技术2022-07-10  106

    103.二叉树的锯齿形层次遍历

    给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

    用一个变量记录层数,奇数尾插,偶数头插。 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { if(root == NULL) return {}; vector<vector<int> > res; queue<TreeNode *> q; int floor = 1; q.push(root); while(!q.empty()){ vector<int> tmp; int length = q.size(); while(length){ TreeNode* cur = q.front(); int data = cur->val; q.pop(); if(floor % 2 == 1){ tmp.push_back(data); } else{ tmp.insert(tmp.begin(),data); } if(cur->left) q.push(cur->left); if(cur->right) q.push(cur->right); length--; } res.push_back(tmp); floor++; } return res; } };

    通过时间:

    Processed: 0.009, SQL: 9