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] ]
==========
按z字输出树节点.
思路:
leetcode上的这种题,都是一个套路,利用BFS遍历方式
要有一个队列queue<TreeNode*> q;保存下一层要访问的节点,
需要一个curr/next计数遍历,curr记录当前层已经访问了几个节点,next记录下一层要访问的节点数量
每访问完一层,需要更新curr和next值,
当访问层数level%2==0时,记录路径反转
=======
code:
/** * 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>> zigzagLevelOrder(TreeNode* root) { vector<vector<int>> re; vector<int> path; if(root==nullptr) return re; help_zig(root,re,path); for(auto i:re){ for(auto j:i){ cout<<j<<" "; }cout<<endl; }cout<<endl; return re; } void help_zig(TreeNode *root,vector<vector<int>> &re,vector<int> &path){ queue<TreeNode*> q; int curr = 1; int next = 0; q.push(root); int level = 0; while(!q.empty()){ if(curr>0){ TreeNode *tmp = q.front(); path.push_back(tmp->val); q.pop(); curr--; if(tmp->left!=nullptr){ q.push(tmp->left); next++; } if(tmp->right!=nullptr){ q.push(tmp->right); next++; } }else{ curr = next; next = 0; if(level%2!=0){ reverse(path.begin(),path.end()); } re.push_back(path); path.clear(); level++; } }///while if(level%2!=0) reverse(path.begin(),path.end()); re.push_back(path); } };
时间: 2024-12-28 01:54:33