地址 https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof/
请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。 例如: 给定二叉树: [3,9,20,null,null,15,7], 3 / 9 20 / 15 7 返回其层次遍历结果: [ [3], [20,9], [15,7] ] 提示: 节点总数 <= 1000
解答
同 32-III 使用BFS
记录完答案后,根据不同的层级进行一次翻转即可
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> ans; int curr = 0; vector<int> v; void bfs(TreeNode* root){ if(root == NULL) return; queue<pair<TreeNode*,int>> q; q.push({root,0}); while(!q.empty()){ TreeNode* p = q.front().first; int level = q.front().second; q.pop(); if(level > curr){ curr=level; if(curr%2==0) reverse(v.begin(),v.end()); ans.push_back(v); v.clear(); v.push_back(p->val); }else{ v.push_back(p->val); } if(p->left!=NULL) q.push({p->left,level+1}); if(p->right!=NULL) q.push({p->right,level+1}); } if((curr+1)%2==0) reverse(v.begin(),v.end()); ans.push_back(v); return; } vector<vector<int>> levelOrder(TreeNode* root) { bfs(root); return ans; } };
DFS也可以
同样是记录完答案后根据层级进行逆转
class Solution { public: vector<vector<int>> ans; void dfs(TreeNode* root,int level){ if(root==NULL) return; if(ans.size() < level){ vector<int> v{root->val}; ans.push_back(v); }else{ ans[level-1].push_back(root->val); } dfs(root->left,level+1);dfs(root->right,level+1); } vector<vector<int>> levelOrder(TreeNode* root) { dfs(root,1); for(int i = 0;i < ans.size();i++){ if(i %2==1){ reverse(ans[i].begin(),ans[i].end()); } } return ans; } };