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

103.二叉树的锯齿形层次遍历 【从头做leetcode|从头做leetcode之leetcode 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> zigzagLevelOrder(TreeNode* root) { if(root == NULL) return {}; vector > res; queue q; int floor = 1; q.push(root); while(!q.empty()){ vector tmp; int length = q.size(); while(length){ TreeNode* cur = q.front(); int data = https://www.it610.com/article/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; } };

通过时间:
从头做leetcode|从头做leetcode之leetcode 103 二叉树的锯齿形层次遍历
文章图片

    推荐阅读