用dfs解决,不用队列也不用双栈。
按之字形顺序打印二叉树
http://www.nowcoder.com/questionTerminal/91b69814117f4e8097390d107d2efbe0
vector<vector<int>>ans;
把line作为层号索引,从0开始,每次遍历到的值直接存到ans[line]就好了。
全部遍历完,如果line是奇数,把ans[line]逆序。</int>
void getLine(TreeNode* root,int line,vector<vector<int>> &ans){//line是根层号
if(root==NULL)
return ;
int size=ans.size();//判断此前是否已经有该行
if(line==size){
vector<int>temp;
ans.push_back(temp);
}
ans[line].push_back(root->val);
int newline=line+1;
getLine(root->left,newline,ans);
getLine(root->right,newline,ans);
}逆序:假设i是行号:
reverse(ans[i].begin(),ans[i].end());
