LintCode 71 二叉树的锯齿形层次遍历
2017-05-04 10:24
411 查看
题目:solveNQueens
要求:
给出一棵二叉树,返回其节点值的锯齿形层次遍历(先从左往右,下一层再从右往左,层与层之间交替进行)样例:
给出一棵二叉树 {3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7 返回其锯齿形的层次遍历为: [ [3], [20,9], [15,7] ]
算法要求:
无解题思路:
在每层判断下是不是该转置。算法如下:
int getSize(TreeNode *root) { if (root == NULL) { return 1; } return getSize(root->left) + getSize(root->right); } vector<vector<int> > zigzagLevelOrder(TreeNode *root) { // write your code here vector<vector<int> > vec; if (root == NULL) { return vec; } int size = getSize(root) - 1; queue<TreeNode*> que; que.push(root); vector<int> *v = new vector<int>(); int n = 1; int i = 0; int j = 0; bool flag = true; while (!que.empty() && j < size) { TreeNode *now = que.front(); que.pop(); i++; if (now) { v->push_back(now->val); j++; } if (i >= n) { i = 0; n *= 2; vector<int> tempVec; if (!flag) { vector<int> tempVec2 = *v; int size2 = v->size(); for (int i = size2 - 1; i >= 0 ; i--) { tempVec.push_back(tempVec2[i]); } } flag = !flag; if (tempVec.empty()) { tempVec = *v; } if (!v->empty()) { vec.push_back(tempVec); v = new vector<int>(); } } if (now) { que.push(now->left); que.push(now->right); } else{ que.push(NULL); que.push(NULL); } } if (!v->empty()) { vector<int> tempVec; if (!flag) { vector<int> tempVec2 = *v; int size2 = v->size(); for (int i = size2 - 1; i >= 0 ; i--) { tempVec.push_back(tempVec2[i]); } } if (tempVec.empty()) { tempVec = *v; } if (!v->empty()) { vec.push_back(tempVec); v = new vector<int>(); } } return vec; } };
相关文章推荐
- lintcode-二叉树的锯齿形层次遍历-71
- LintCode-剑指Offer-(71)二叉树的锯齿形层次遍历
- LintCode:二叉树的锯齿形层次遍历
- 二叉树的锯齿形层次遍历,lintcode
- lintcode: 二叉树的锯齿形层次遍历
- Lintcode 二叉树的锯齿形层次遍历
- 71 - 二叉树的锯齿形层次遍历
- 二叉树的锯齿形层次遍历-LintCode
- LintCode 二叉树的锯齿形层次遍历
- [Lintcode]Binary Tree Level Order Traversal II 二叉树的层次遍历 II
- LintCode:二叉树的层次遍历
- lintcode-二叉树的层次遍历II-70
- lintcode-二叉树的层次遍历 II
- 二叉树的锯齿形层次遍历
- 【LintCode 简单】69. 二叉树的层次遍历
- lintcode 二叉树的层次遍历
- Binary Tree Zigzag Level Order Traversal (二叉树锯齿形层次遍历)
- python_lintcode_69二叉树的层次遍历
- LintCode 69-二叉树的层次遍历
- LintCode 69 二叉树的层次遍历