Leetcode:binary Tree Zigzag level Order traversal

Source: Internet
Author: User

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

Return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
Analysis
Assuming after traversing the 1st level, nodes in queue is {9, 20, 8},
And we are going to traverse 2nd level, which was even line and should print value from right to left [8, 20, 9].

We know there is 3 nodes in the current queue,
So the vector for this level in final result should is of size 3.
Then, the queue [i], goes to, Vector[queue.size ()-1-i] i.e.
The ith node in current queue should is placed in (Queue.size ()-1-i) position on vector for.

For example, for node (9), it's index in the queue is 0, so it's index in vector should be (3-1-0) = 2.
Code

 vector<vector<int> >Zigzaglevelorder (treenode* root) {if(Root = NULL) {return  vector<vector<int> >(); } vector<vector<int> >Result queue<TreeNode*>Nodesqueue; Nodesqueue.push (root);BOOLLeftToRight =true; while(!nodesqueue.empty ()) {intSize = Nodesqueue.size (); vector<int>row (size); for(inti =0; i < size;            i++) {treenode* node = Nodesqueue.front (); Nodesqueue.pop ();//Find position to fill node ' s value            intindex = (lefttoright)? I: (Size-1-i); Row[index] = node->val;if(Node->left)            {Nodesqueue.push (node->left); }if(Node->right)            {Nodesqueue.push (node->right); }        }// after this levelLeftToRight =!lefttoright;    Result.push_back (row); }returnResult;}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode: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.