二叉树Z型输出
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]
]
其实还是广度优先遍历,只不过这里对偶数行需要reverse一下,
发现stl可以方便地完成reverse(row.begin(),row.end())即可
然后也要注意这类题目需要知道递归的怎么写。
其实递归就是传入一个level来判断当前进入到了第几层,然后再将数据存入到这一层中
class Solution {
public:
//递归版本
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int> > result;
tranverse(root,0,result);
for(int i=0;i<result.size();i++)
if(i&0x01) reverse(result[i].begin(),result[i].end());
return result;
}
void tranverse(TreeNode* root,int level,vector<vector<int> > &result){
if(root==NULL) return;
if(level>=result.size())
result.push_back(vector<int> ());
result[level].push_back(root->val);
tranverse(root->left,level+1,result);
tranverse(root->right,level+1,result);
}
//非递归版
// vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
// vector<vector<int> > result;
// if(!root) return result;
// queue<TreeNode*> Q;
// Q.push(root);
// int count=0;
// while(!Q.empty()){
// queue<TreeNode*> Qnext;
// vector<int> row;
// while(!Q.empty()){
// TreeNode* node=Q.front();
// Q.pop();
// row.push_back(node->val);
// if(node->left) Qnext.push(node->left);
// if(node->right) Qnext.push(node->right);
// }
// if(count & 0x01) reverse(row.begin(),row.end());
// result.push_back(row);
// Q=Qnext;
// count++;
// }
// return result;
// }
};
字符串Z型输出——原题
上面的题是由这道题演化而来的
The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: “PAHNAPLSIIGYIR”
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.
题意很简单,很像之前让自己排列并输出一些数据
于是主要就是找规律了~
class Solution {
public:
string convert(string s, int numRows) {
int n=s.size();
if(n<=1) return s;
if(numRows<=1) return s;
string target="";
for(int i=0;i<numRows;i++){
for(int j=i,count=1;j<n;j+=2*numRows-2,count++){
target=target+s[j];
if(j+(numRows-i-1)*2<n && i>0 && i>0 && i<numRows-1)
target=target+s[j+(numRows-i-1)*2];
}
}
return target;
}
};