题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; */ #include <unistd.h> #include <vector> class Solution { public: vector<vector<int>> creat(TreeNode* pRoot){ vector<vector<int>> ans; if(pRoot==nullptr){ return ans; } vector<int> t(1,pRoot->val); ans.push_back(t); vector<vector<int>> vecl=creat(pRoot->left); vector<vector<int>> vecr=creat(pRoot->right); for(int i=0;i<vecl.size();i++){ if(i<vecr.size()){ for(int j=0;j<vecr[i].size();j++){ vecl[i].push_back(vecr[i][j]); } } ans.push_back(vecl[i]); } if(vecr.size()>vecl.size()){ for(int i=vecl.size();i<vecr.size();i++){ ans.push_back(vecr[i]); } } return ans; } vector<vector<int>> Print(TreeNode* pRoot){ vector<vector<int>> ans=creat(pRoot); for(int i=1;i<ans.size();i+=2){ vector<int> t; for(int j=ans[i].size()-1;j>=0;j--){ t.push_back(ans[i][j]); } ans[i]=t; } return ans; } };