Subsequent binary search tree traversal sequence; a zigzag binary print

Here Insert Picture Description
Problem-solving ideas:

This question is not the first time the idea is very simple Once you have the idea
that, after traversing the last element in the sequence is the root node, and then re-iterate through the entire sequence of
the sequence, once met with a number greater than the node, then it is no longer possible We encountered a number less than the root node, and once met, it shows that the subsequent traversal sequence is not qualified binary search tree

class Solution {
public:
        bool VerifySquenceOfBST(vector<int> sequence) {
	    if (sequence.empty())
		    return false;
	    int root = sequence.back();
	    int size = sequence.size();
	    int i;
	    for (i = 0; i < size; ++i)
	    {
		    if (sequence[i] > root)
		    {
			    break;
		    }
	    }
	    for (i; i < size; ++i)
	    {
		    if (sequence[i] < root)
		    {
			    return false;
		    }
	    }
	    return true;
    }
};

The second question
Here Insert Picture Description
problem-solving ideas:
before, the two-dimensional array traversal sequence in accordance with, and then each layer in an array, and finally a two-dimensional array coming out of the idea is the same, only need to add the final step, after a two-dimensional array to get every line of conduct in reverse, on the line.

/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
	vector<vector<int> > Print(TreeNode* pRoot) {
		vector<vector<int>> vec1;
		if (pRoot == nullptr)
			return vec1;
		queue<TreeNode*> que;
		que.push(pRoot);
		
		int count = 1;  //用来记录本层,进入队列的个数。刚开始的时候队列中已经有了一个元素
		int size = 0;  //用来记录下一层元素的个数
		while (!que.empty())  //当队列不为空就一直循环
		{
			vector<int> vec2;    //最后要插入二维数组的一维数组
			while (count)  //当
			{
				TreeNode* p = que.front();
				if (p->left)
				{
					que.push(p->left);
					size++;  //每进入一个元素+1,记录的是本层元素个数
				}
				if (p->right)
				{
					que.push(p->right);
					size++;
				}
				que.pop();
				vec2.push_back(p->val);
				count--;  //每出一个元素,上一层进入的元素就减减,等到了0,就说明,上一层进入元素都出去了
			}
			count = size;  //让本层个数在下次循环中,变成上一层。数据交换
			size = 0;
			vec1.push_back(vec2);
		}
		for (int i = 1; i < vec1.size(); i += 2)   //每隔一样进行逆序的代码
		{
			reverse(vec1[i].begin(), vec1[i].end());
		}
		return vec1;
	}

};

More important is that double loop while
the outer loop termination condition is that the queue is empty
inner loop termination condition is that the last element of the stack into the circulation, are traversed (traversed mean, his left and right subtrees It is already stored in a queue, while he has been pressed into a one-dimensional array)

Published 230 original articles · won praise 28 · views 9298

Guess you like

Origin blog.csdn.net/weixin_43767691/article/details/103863905