Leecode 103 二叉树的锯齿形层次遍历

讲下思路:*非递归**,双栈

  • 利用栈1s1储存奇数层的点,s2储存偶数层的点,所以根结点就储存在s2里;
  • 当前层为偶数层时,说明此时s1是空的,为了让下一层结点从s1出来的时候从右到左,所以让左结点先进栈,毕竟先进后出嘛;
  • 当前层为奇数层时,说明此时s2是空的,且s1结点出来时从右到左,为了让下一层结点从s2出来的时候从左到右,所以让右结点先进栈,先进后出;
  • 记得每次层数+1,将本层结点用一个vector储存。
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector> zigzagLevelOrder(TreeNode* root) {
        vector> ans;
        if(root==NULL) return ans;
        
        stack s1;
        stack s2;
        s1.push(root);
        int height=1;
        while(!s1.empty()||!s2.empty())
        {
            int size;
            if(height%2==1) size=s1.size();
            else size=s2.size();
            vector tmp;
            while(size--)
            {
                if(height%2==1)
                {
                    TreeNode* node=s1.top();
                    tmp.push_back(node->val);
                    s1.pop();
                    if(node->left) s2.push(node->left);
                    if(node->right) s2.push(node->right);
                }
                
                if(height%2==0)
                {
                    TreeNode* node=s2.top();
                    tmp.push_back(node->val);
                    s2.pop();
                    if(node->right) s1.push(node->right);
                    if(node->left) s1.push(node->left);
                }
            }
            height++;
            ans.push_back(tmp);
        }
        return ans;
    }
    
};

 

你可能感兴趣的:(Leetcode)