按之字形顺序打印二叉树

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

题目描述

请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。

代码1:

偶数层对节点先插入右节点,再插入左节点,奇数层先插入左节点,再插入右节点

所有层都是从顶到尾(vector)

class Solution
{
public:
    vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int>> res;
        if(pRoot == NULL) return res;
        int numOfPos = 0;
        vector<TreeNode*> tmpStorage;
        tmpStorage.push_back(pRoot);
        while(tmpStorage.size())
        {
            vector<int> resLittle;
            int number = tmpStorage.size();
            for(int i = 0;i < number;i++)
            {
                resLittle.push_back(tmpStorage[i]->val);
            }
            res.push_back(resLittle);
 
            vector<TreeNode*> tempNextPos;
            if(numOfPos%2 == 0)
            {
                for(int i = number-1;i >= 0;i--)
                {
                    if(tmpStorage[i]->right) tempNextPos.push_back(tmpStorage[i]->right);
                    if(tmpStorage[i]->left) tempNextPos.push_back(tmpStorage[i]->left);
                }
            }
            else if(numOfPos%2 == 1)
            {
                for(int i = number-1;i >= 0;i--)
                {
                    if(tmpStorage[i]->left) tempNextPos.push_back(tmpStorage[i]->left);
                    if(tmpStorage[i]->right) tempNextPos.push_back(tmpStorage[i]->right);
                }
            }
            tmpStorage.clear();
            for(int i = 0;i < tempNextPos.size();i++)
            {
                tmpStorage.push_back(tempNextPos[i]);
            }
            numOfPos++;
        }
        return res;
    }
     
};

代码2:

使用递归实现

class Solution {
public:
	vector<vector<int>> res;
    vector<vector<int> > Print(TreeNode* pRoot)
     {
    	if(pRoot == NULL)	return res;
    	vector<TreeNode*> storageNode;
    	storageNode.push_back(pRoot);
    	printHelper(storageNode,0);
    	return res;
    }
    void printHelper(vector<TreeNode*> storageNode,int num)
    {
    	if(storageNode.empty()) return;
    	vector<TreeNode*> storageNodeTmp;
    	vector<int> storageNum;
		for(int i = 0;i < storageNode.size();i++)
		{
			storageNum.push_back(storageNode[i]->val);
		}
		res.push_back(storageNum);
		if(num%2 == 0)
		{
			for(int i = storageNode.size()-1;i >= 0;i--)
			{
				if(storageNode[i]->right) storageNodeTmp.push_back(storageNode[i]->right);
				if(storageNode[i]->left) storageNodeTmp.push_back(storageNode[i]->left);
			}
		}
		if(num%2 == 1)
		{
			for(int i = storageNode.size()-1;i >= 0;i--)
			{
				if(storageNode[i]->left) storageNodeTmp.push_back(storageNode[i]->left);
				if(storageNode[i]->right) storageNodeTmp.push_back(storageNode[i]->right);
			}
		}
		num++;
		printHelper(storageNodeTmp,num);
    }
};

 

展开阅读全文

没有更多推荐了,返回首页