lc 二叉树的锯齿形层次遍历
链接:https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/
代码:
/** * 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 == nullptr) return {}; vector<vector<int>> res; vector<TreeNode*> v; v.push_back(root); int ltor = 1; while(1) { int vn = v.size(); if(ltor) { // cout << vn << endl; vector<int> temp_res; for(int i = 0; i < vn; i++) { temp_res.push_back(v[i]->val); } res.push_back(temp_res); } else { vector<int> temp_res; for(int i = vn-1; i >= 0; i--) { temp_res.push_back(v[i]->val); } res.push_back(temp_res); } vector<TreeNode*> temp_v; for(int i = 0; i < vn; i++) { if(v[i]->left) temp_v.push_back(v[i]->left); if(v[i]->right) temp_v.push_back(v[i]->right); } int temp_len = temp_v.size(); if(!temp_len) break; v.clear(); for(int i = 0; i < temp_len; i++) { v.push_back(temp_v[i]); } ltor = !ltor; } return res; } };
思路:层序遍历即可
posted on 2020-05-25 01:00 FriskyPuppy 阅读(71) 评论(0) 编辑 收藏 举报