Title Link: 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},
3 / \ 9 20 / \ 15
Return its zigzag level order traversal as:
[ [3], [20,9],
Confused what "{1,#,2,3}" means? > read more about how binary tree was 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 ex Ists below.
Here's an example:
1 / \ 2 3 / 4 \
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
The requirement of this problem is to traverse the binary tree zigzag way, that is, layered traversal, first from left to right, then from right to left, then from left to right, then from right to left, and so on.
Similar to binary Tree level Order traversal, it is necessary to introduce variable N to record the number of nodes per layer, since each layer's nodes need to be placed in the array separately. However, due to the need to traverse in zigzag way, it is necessary to reverse the even layer (assuming the root node is layer 12th). What's left is the breadth-first method of traversal.
Time complexity: O (N)
Space complexity: O (N)
1 class Solution2 {3 Public:4 Vector<Vector<int> > Zigzaglevelorder(TreeNode *Root)5 {6 Vector<Vector<int> > Vvi;7 8 if(Root == NULL)9 return Vvi;Ten One Queue<TreeNode *> Q; A Q.Push(Root); - BOOL Zigzag = false; - while(!Q.Empty()) the { - Vector<int> VI; - for(int I = 0, N = Q.size(); I < N; ++ I) - { + TreeNode *Temp = Q.Front(); - Q.Pop(); + if(Temp - Left != NULL) A Q.Push(Temp - Left); at if(Temp - Right != NULL) - Q.Push(Temp - Right); - VI.push_back(Temp - Val); - } - if(Zigzag) - Reverse(VI.begin(), VI.End()); in Vvi.push_back(VI); - Zigzag = !Zigzag; to } + - return Vvi; the } * };
Reprint please indicate source: Leetcode---103. Binary Tree Zigzag level Order traversal
Leetcode---103. Binary Tree Zigzag level Order traversal