Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:Given binary tree [3,9,20,null,null,15,7],
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]---------------------------------------------------------------------------------------------------------------------
这个是在leetcode102. Binary Tree Level Order Traversal的基础上拓展来的,只要加一个判断就行。
C++代码:
/** * 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) return {}; queue<TreeNode*> q; q.push(root); vector<vector<int> > vec; bool flag = true; while(!q.empty()){ vector<int> v; for(int i = q.size(); i > 0; i--){ auto t = q.front(); q.pop(); v.push_back(t->val); if(t->left) q.push(t->left); if(t->right) q.push(t->right); } if(!flag) reverse(v.begin(),v.end()); flag = !flag; vec.push_back(v); } return vec; } };
转载于:https://www.cnblogs.com/Weixu-Liu/p/10792718.html