【算法】JZ77 按之字形顺序打印二叉树

给定一个二叉树,返回该二叉树的之字形层序遍历,(第一层从左向右,下一层从右向左,一直这样交替)

题解

/*
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>> vv;
        if(nullptr == pRoot)
            return vv;
        
        stack<TreeNode*> st;
        queue<TreeNode*> q;
        vector<int> v;
        int dir = 1; // 1:left->right 2:right->left
        st.push(pRoot);
        
        while(!st.empty())
        {
          
   
            // 出栈
            while(!st.empty())
            {
          
   
                TreeNode* tmp = st.top(); // 保存栈顶元素
                v.push_back(tmp->val);
                st.pop();
                TreeNode* first = (dir == 1) ? tmp->left : tmp->right;
                TreeNode* right = (dir == 1) ? tmp->right : tmp->left;
                if(first)
                    q.push(first);
                if(right)
                    q.push(right);
            }
            // 队列中的数据转移到栈中
            while(!q.empty())
            {
          
   
                st.push(q.front());
                q.pop();
            }
            // 修改dir
            dir = (dir == 1) ? 2 : 1;
            vv.push_back(v);
            v.clear();
        }
        return vv;
    }
    
};

注意点

1、使用栈和队列

stack<TreeNode*> st;
queue<TreeNode*> q;

2、dir的修改

3、左右结点的确定

TreeNode* first = (dir == 1) ? tmp->left : tmp->right;
TreeNode* right = (dir == 1) ? tmp->right : tmp->left;
经验分享 程序员 微信小程序 职场和发展