1. 程式人生 > >按之字形順序列印二叉樹 c++實現

按之字形順序列印二叉樹 c++實現

題目描述

請實現一個函式按照之字形列印二叉樹,即第一行按照從左到右的順序列印,第二層按照從右至左的順序列印,第三行按照從左到右的順序列印,其他行以此類推。

/*
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> > result;
        vector<int> item;
        if(pRoot==NULL) return result;
        queue<pair<TreeNode*,int> > Q;//奇數層輸出 ,從左到右
        Q.push(make_pair(pRoot,1));
        int is_put=0;
        int new_deep=0;
        while(!Q.empty())
        {
            int deep=Q.front().second;
            TreeNode* node=Q.front().first;
            if(item.size()==0)
            {
                item.push_back(node->val);
                new_deep=deep;
            }else
            {
                if(new_deep!=deep)
                {
                    if(new_deep%2==0)
                    {
                        jiaohuan(item);
                    }
                    result.push_back(item);
                    item.clear();
                    item.push_back(node->val);
                    new_deep=deep;
                }else
                {
                    item.push_back(node->val);
                }
            }

            Q.pop();
            if(node->left)
            {
                Q.push(make_pair(node->left,deep+1));
            }
            if(node->right)
            {
                Q.push(make_pair(node->right,deep+1));
            }

        }
        if(item.size()!=0)
        {
            if(new_deep%2==0)
            {
                jiaohuan(item);
            }
            result.push_back(item);
        }
        return result;

    }
private:
    void jiaohuan(vector<int>& item)
    {
        int i=0;
        int j=item.size()-1;
        while(i<j)
        {
            int T=item[i];
            item[i]=item[j];
            item[j]=T;
            i++;j--;
        }
    }
};