[LeetCode] 103. Binary Tree Zigzag Level Order Traversal 二叉树的之字形层序遍历
本题是 102 题的简单变形
方法一:
将102题的结果的偶数层节点(第2,4,6,...)vector内的元素翻转下即可;数组的翻转可以直接使用c++ stl 的std::reverse实现,
代码如下:
1 /* 2 * @Descripttion: 3 * @version: 4 * @Author: wangxf 5 * @Date: 2020-07-07 20:14:29 6 * @LastEditors: Do not edit 7 * @LastEditTime: 2020-07-07 22:19:22 8 */ 9 /* 10 * @lc app=leetcode.cn id=103 lang=cpp 11 * 12 * [103] 二叉树的锯齿形层次遍历 13 */ 14 15 // @lc code=start 16 /** 17 * Definition for a binary tree node. 18 * struct TreeNode { 19 * int val; 20 * TreeNode *left; 21 * TreeNode *right; 22 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 23 * }; 24 */ 25 struct NodeInfo 26 { 27 TreeNode* ptr = nullptr; 28 int level = 0; 29 NodeInfo(TreeNode* node_ptr,int node_level): 30 ptr(node_ptr),level(node_level) 31 {} 32 }; 33 34 class Solution { 35 public: 36 vector<vector<int>> zigzagLevelOrder(TreeNode* root) 37 { 38 std::vector<vector<int>> res; 39 if(!root) return res; 40 std::queue<NodeInfo> q; 41 NodeInfo root_node(root,0); 42 q.push(root_node); 43 while(!q.empty()) 44 { 45 NodeInfo cur_node = q.front(); 46 q.pop(); 47 int cur_level = cur_node.level; 48 int cur_node_val = cur_node.ptr->val; 49 if(res.size()<cur_level+1) 50 { 51 vector<int> tempVec; 52 res.push_back(tempVec); 53 } 54 res[cur_level].push_back(cur_node_val); 55 if(cur_node.ptr->left) 56 { 57 NodeInfo leftNode(cur_node.ptr->left,cur_level+1); 58 q.push(leftNode); 59 } 60 if(cur_node.ptr->right) 61 { 62 NodeInfo rightNode(cur_node.ptr->right,cur_level+1); 63 q.push(rightNode); 64 } 65 } 66 int res_size = res.size(); 67 for(int i = 0;i<res_size;++i) 68 { 69 if(i%2!=0){ 70 std::reverse(res[i].begin(),res[i].end()); 71 } 72 } 73 return res; 74 } 75 }; 76 // @lc code=end