[LeetCode] 103. Binary Tree Zigzag Level Order Traversal

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

 

return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]

题目要求对二叉树进行呈Z字状的层序遍历。从上到下的双数层(包括0层)从左向右排列,单数层从右向左排列。
该题是层序遍历的变体,可以根据当前的层数的奇偶作为标志进行层序遍历。
方法一:使用递归的方法进行遍历
使用level确定插入元素在结果数组中的位置。
根据奇偶层不同分别从前方和后方推入元素。奇数层从后方推入,偶数层从前方推入。
代码如下:
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> res={};
        zOrder(root,0,res);
        return res;
    }
    void zOrder(TreeNode *root,int level,vector<vector<int>> &res){
        if(!root)return;
        if(res.size()<level+1)res.push_back({});
        if(level%2!=0){
            res[level].insert(res[level].begin(),root->val);
        }
        else{
            res[level].push_back(root->val);
        }
        if(root->left){zOrder(root->left,level+1,res);}
        if(root->right){zOrder(root->right,level+1,res);}
        return;
    }
};

方法二:使用堆记录该层的元素

维护两个对,相邻的层将元素存入不同的堆中,存入的顺序相反,最后将堆中的数字顺序放入结果数组中即可。

代码如下:

class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> res={};
        
        if(!root)return res;
        stack<TreeNode*> s1;
        stack<TreeNode*> s2;
        s1.push(root);
        vector<int> out;
        while(!s1.empty() || !s2.empty()){
            while(!s1.empty()){
                TreeNode* cur=s1.top();
                s1.pop();
                out.push_back(cur->val);
                if(cur->left)s2.push(cur->left);
                if(cur->right)s2.push(cur->right);
            }
            if(!out.empty())res.push_back(out);
            out.clear();
            
            while(!s2.empty()){
                TreeNode* cur=s2.top();
                s2.pop();
                out.push_back(cur->val);
                if(cur->right)s1.push(cur->right);
                if(cur->left)s1.push(cur->left);
            }
            if(!out.empty())res.push_back(out);
            out.clear();
        }
        return res;
    }
};

 

posted @ 2019-05-23 20:36  程嘿嘿  阅读(188)  评论(0编辑  收藏  举报