关闭

103. Binary Tree Zigzag Level Order Traversal

81人阅读 评论(0) 收藏 举报
分类:

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]
]

我们发现一个规律,奇数正序,偶数反序,所以获取到每个层次的元素就可以ac了。

/**
 * 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<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int> > outer;
        vector<int> inner;
        queue<TreeNode*> q;
        if (root)
           q.push(root);
        else
           return outer;
        int k=1;
        while (!q.empty())
        {
            int size=q.size();
            inner.clear();
            while (size-->0)
            {
                TreeNode* t=q.front();
                q.pop();
                inner.push_back(t->val);
                if (t->left)
                   q.push(t->left);
                if (t->right)
                   q.push(t->right);
            }
            if (k%2)
               outer.push_back(inner);
            else
            {
                reverse(inner.begin(),inner.end());
                outer.push_back(inner);
            }
            k++;
        }
        return outer;
    }
};


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:71960次
    • 积分:1834
    • 等级:
    • 排名:千里之外
    • 原创:96篇
    • 转载:107篇
    • 译文:1篇
    • 评论:9条
    最新评论