Leetcode[tree]: Binary Tree Zigzag level Order traversal

Source: Internet
Author: User

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],< BR style= "" >[20,9],
[15,7]
"

My iterative solution is as follows:

vector<vector<int> > Zigzaglevelorder (TreeNode *root) {    vector<vector<int> > res;    Vector<treenode *> iter;    if (root) iter.push_back (root);    int isforward = 1;    while (!iter.empty ()) {        int size = Iter.size ();        Vector<int> level;        for (int i = 0; i < size; ++i) {            level.push_back (iter[i]->val);            if (iter[i]->left) iter.push_back (iter[i]->left);            if (iter[i]->right) iter.push_back (iter[i]->right);        }        if (!isforward) reverse (Level.begin (), Level.end ());        Res.push_back (level);        Iter.erase (Iter.begin (), Iter.begin () + size);        Isforward ^= 0x01;    return res;}


My recursive solution is as follows:

Class Solution {public:    vector<vector<int> > Zigzaglevelorder (TreeNode *root) {        res.clear ();        if (!root) return res;        Zigzaglevelorder (root, 1);        return res;    } Private:    vector<vector<int> > Res;    void Zigzaglevelorder (TreeNode *root, int level) {        if (res.size () < level) res.resize (level);        if (level% 2) res[level-1].push_back (root->val);        Else Res[level-1].insert (Res[level-1].begin (), root->val);        if (root->left) Zigzaglevelorder (Root->left, level + 1);        if (root->right) Zigzaglevelorder (root->right, level + 1);    }};


The time performance of the two algorithms is the same as shown in:


Leetcode[tree]: Binary Tree Zigzag level Order traversal

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.