[B] [C] [D]
Given a binary tree, return a zigzag sequence traversal of its node values. (that is, the next layer is traversed from left to right, then right to left, and so on, alternating between layers).
For example, given a binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
Copy the code
Return the zigzag sequence traversal as follows:
[[3], [20,9], [15,7]Copy the code
The binary tree traversal is a binary tree traversal. The binary tree traversal is a binary tree traversal.
- Create the result array
- In the recursive traversal process of ordinary binary tree, the depth of the corresponding node is passed in, and the node value is inserted into the corresponding subarray of the result array according to the depth of the current node
- Return an array of results
To complete the zigzag sequence traversal, you only need to traverse left to right on even rows and right to left on odd rows.
We don’t really need to switch the traversal order here, we just need to determine whether the current depth is odd or even when the node values are inserted into the subarray. If it is even, push the node values into the end of the subarray. If it is odd, unshift the result values into the beginning of the subarray
The code is as follows:
Var zigzagLevelOrder = function(root) {const res = []; Function preorder(node,deep){if(node === null) return; // If the current depth subarray is not created, create a subarray if(! res[deep]) res[deep] = []; If (deep%2) res[deep].unshift(node.val); // If the current depth is even, record the node value from left to right else res[deep].push(node.val); Preorder (node. Left,deep+1); preorder(node.right,deep+1); } // call preorder(root,0); // return result array return res; };Copy the code
At this point we have completed the zigzag sequence traversal of leetcode-103-binary tree
If you have any questions or suggestions, please leave a comment!