LeetCode-Binary Tree Zigzag Level Order Traversal

来源:互联网 发布:数据分析师东华软件 编辑:程序博客网 时间:2024/05/29 11:56

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,#,#,15,7},

    3   / \  9  20    /  \   15   7

return its zigzag level order traversal as:

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

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1  / \ 2   3    /   4    \     5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
Solution:

Code:

<span style="font-size:14px;">/** * Definition for binary tree * 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> > results;        if (!root) return results;        vector<queue<TreeNode *> > q(2, queue<TreeNode *>());        int index = 0;        q[index].push(root);        while (!q[index].empty()) {            vector<int> result;            while (!q[index].empty()) {                root = q[index].front();                q[index].pop();                result.push_back(root->val);                if (root->left) q[(index+1)%2].push(root->left);                if (root->right) q[(index+1)%2].push(root->right);            }            if (index) reverse(result.begin(), result.end());            index = (index+1)%2;            results.push_back(result);        }        return results;    }};</span>



0 0
原创粉丝点击