Advertisement
vkreal

Untitled

Jun 21st, 2022
807
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
  2.  
  3. var height = function(root) {
  4.     if(!root) return 0;
  5.     return Math.max(height(root.left), height(root.right)) + 1;
  6. }
  7. var dfs = function(root, index, res) {
  8.     if(!root) return;
  9.     if(index == 0) res.push(root.val);
  10.     dfs(root.left, index-1, res);
  11.     dfs(root.right, index-1, res);
  12. }
  13. var zigzagLevelOrder = function(root) {
  14.     let h = height(root);
  15.     let ans = [];
  16.     for(let i=0; i<h; i++) {
  17.         let level = [];
  18.         dfs(root, i, level);
  19.         ans.push(level);
  20.     }
  21.     for(let i=0; i<ans.length; i++) {
  22.         if(i % 2 != 0) {
  23.             ans[i].reverse();
  24.         }
  25.     }
  26.     return ans;
  27. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement