Leetcode Binary Tree Zigzag Level Order Traversal

Binary Tree Zigzag Level Order Traversal

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,#,#,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.


我使用了两个deque容器做,其实可以使用stack。

代码还是非常清晰的,一块一块的分好,思路很容易跟的。

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;
	}
};








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值