1. 题⽬链接:103.⼆叉树的锯⻮形层序遍历
2. 题⽬描述:
3. 解法(层序遍历):
算法思路:
在正常的层序遍历过程中,我们是可以把⼀层的结点放在⼀个数组中去的。 既然我们有这个数组,在合适的层数逆序就可以得到锯⻮形层序遍历的结果。
C++算法代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root)
{
vector<vector<int>>answer; //最终返回值
//判断空树
if(root==nullptr)
{
return answer;
}
queue<TreeNode*>temp; //存储一层中需要访问的节点
temp.push(root);
//没有需要遍历的节点则结束遍历
int key_num=1; //判断该层是否需要逆序
while(temp.size())
{
int num=temp.size();
//遍历一层的节点
vector<int>t;
key_num*=-1;
for(int i=0;i<num;i++)
{
TreeNode* n=temp.front();
t.push_back(n->val);
//加入访问节点的孩子节点
if(n->left)
{
temp.push(n->left);
}
if(n->right)
{
temp.push(n->right);
}
//释放被访问过的节点
temp.pop();
}
//判断+更新答案
if(key_num==-1)
{
answer.push_back(t);
}
else
{
//翻转数组
reverse(t.begin(),t.end());
answer.push_back(t);
}
}
return answer;
}
};
Java算法代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution
{
public List<List<Integer>> zigzagLevelOrder(TreeNode root)
{
List<List<Integer>> ret = new ArrayList<>();
if (root == null) return ret;
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
int level = 1;
while (!q.isEmpty())
{
int sz = q.size();
List<Integer> tmp = new ArrayList<>();
for (int i = 0; i < sz; i++)
{
TreeNode t = q.poll();
tmp.add(t.val);
if (t.left != null) q.add(t.left);
if (t.right != null) q.add(t.right);
}
// 判断是否逆序
if (level % 2 == 0) Collections.reverse(tmp);
ret.add(tmp);
level++;
}
return ret;
}
}