Leetcode Binary Tree Zigzag Level Order Traversal

本文介绍了一种解决二叉树锯齿形层序遍历问题的方法,利用双端队列和栈交替进行节点存储,实现从左至右再从右至左的遍历方式,适用于算法竞赛及面试准备。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Binary Tree Zigzag Level Order Traversal

Given a binary tree, return thezigzag level ordertraversal 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,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]

confused what"{1,#,2,3}"means?> read more on how binary tree is serialized on OJ.

二叉树层序遍历的知识。

使用什么容器可以任君选择。

关键是考查层与层之间的访问顺序是不一样的,需要做一点特殊处理。

总体来说3到4星难度。

class Solution {
public:
	vector<vector<int> > zigzagLevelOrder(TreeNode *root) 
	{
		vector<vector<int> > v;
		if (!root) return v;

		deque<TreeNode *> qt1;
		deque<TreeNode *> qt2;
		qt1.push_back(root);

		vector<int> itmedia;
		itmedia.push_back(root->val);
		v.push_back(itmedia);
		itmedia.clear();

		while (!qt1.empty())
		{
			while (!qt1.empty())
			{
				TreeNode *t = qt1.back();
				qt1.pop_back();
				if (t->right)
				{
					qt2.push_back(t->right);
					itmedia.push_back(t->right->val);
				}
				if (t->left)
				{
					qt2.push_back(t->left);
					itmedia.push_back(t->left->val);
				}
			}
			if (!itmedia.empty()) v.push_back(itmedia);
			itmedia.clear();
			while (!qt2.empty())
			{
				TreeNode *t = qt2.back();
				qt2.pop_back();
				if (t->left)
				{
					qt1.push_back(t->left);
					itmedia.push_back(t->left->val);
				}
				if (t->right)
				{
					qt1.push_back(t->right);
					itmedia.push_back(t->right->val);
				}
			}
			if (!itmedia.empty()) v.push_back(itmedia);
			itmedia.clear();
		}
		return v;
	}
};


//2014-2-16 update
	vector<vector<int> > zigzagLevelOrder(TreeNode *root) 
	{
		vector<vector<int> > rs;
		if (!root) return rs;
		stack<TreeNode *> stk[2];
		stk[0].push(root);
		bool flag = false;
		while (!stk[flag].empty())
		{
			rs.push_back(vector<int>());
			while (!stk[flag].empty())
			{
				TreeNode * t = stk[flag].top();
				stk[flag].pop();
				rs.back().push_back(t->val);
				if (flag)
				{
					if (t->right) stk[!flag].push(t->right);
					if (t->left) stk[!flag].push(t->left);
				}
				else
				{
					if (t->left) stk[!flag].push(t->left);
					if (t->right) stk[!flag].push(t->right);
				}
			}
			flag = !flag;
		}
		return rs;
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值