[leetCode]Binary Tree Zigzag Level Order Traversal
跟着
Binary Tree Level Order Traversal
Binary Tree Level Order Traversal II
这两题做下来基本AC没什么难度,题还是连着做顺手。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ #include <list> #include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: list<vector<TreeNode>> levelNode; vector<vector<int>> allLevelval; vector<vector<int>> zigzagLevelOrder(TreeNode *root) { vector<TreeNode> curVec; vector<int> curIntList; if(levelNode.empty() && root != NULL){ curVec.push_back(*root); levelNode.push_back(curVec); } bool zigzag = true; for(list<vector<TreeNode>>::iterator iter = levelNode.begin();iter != levelNode.end();iter++){ int size = iter->size(); curVec.clear(); curIntList.clear(); for(int i = 0 ; i< size; i++){ TreeNode curNode = iter->at(i); if(curNode.left != NULL) curVec.push_back(*curNode.left); if(curNode.right != NULL) curVec.push_back(*curNode.right); if(zigzag){ curIntList.push_back(curNode.val); }else{ curIntList.insert(curIntList.begin(),curNode.val); } } allLevelval.push_back(curIntList); if(curVec.empty()) break; levelNode.push_back(curVec); zigzag = !zigzag; } return allLevelval; } };
艰难的成长