剑指offer--之型打印二叉树

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Android_chunhui/article/details/88862382

题目:
按之打印二叉树
在这里插入图片描述

class Solution {
	/*
	* 这题与层次遍历类似,层次遍历是使用一个队列完成。
	本题画图后观察,规律应该是依靠两个栈完成,奇数层一个偶数曾一个,还是一处一个节点后,将他的左右孩子加入下一层的
	栈中,不过奇数层时要先加右孩子。
	*/
public:
	vector<vector<int> > Print(TreeNode* pRoot) {
		stack<TreeNode*> s1, s2;
		vector<vector<int> > ret;
		if (pRoot == NULL)
			return ret;
		s1.push(pRoot);

		int i = 2;
		while (s1.empty() == false || s2.empty() == false)
		{
			if (i % 2 == 0)
			{
				vector<int> t;
				while (s1.empty() == false)
				{
					TreeNode* top = s1.top();
					s1.pop();
					t.push_back(top->val);
					if (top->left) s2.push(top->left);
					if (top->right) s2.push(top->right);
				}
				ret.push_back(t);
			}
			else {
				vector<int> t;
				while (s2.empty() == false)
				{
					TreeNode* top = s2.top();
					s2.pop();
					t.push_back(top->val);
					if (top->right) s1.push(top->right);
					if (top->left) s1.push(top->left);
				}
				ret.push_back(t);
			}
			++i;
		}
		return ret;
	}

};

猜你喜欢

转载自blog.csdn.net/Android_chunhui/article/details/88862382
今日推荐