leetcode

Leetcode submissions
git clone git://git.laack.co/leetcode.git
Log | Files | Refs | README

invert-binary-tree.js (1446B)


      1 //For each split in a binary tree place the right node on the left
      2 //and the left node on the right. Then return the final result
      3 //To do this I used BFS to swap each node as I made by way down the tree
      4 //The time complexity of this code is O(n) where n is the number of nodes in the tree
      5 //Time: 55ms Beats: 79.68%
      6 //Memory: 42.9MB Beats: 5.29%
      7 
      8 /**
      9  * Definition for a binary tree node.
     10  * function TreeNode(val, left, right) {
     11  *     this.val = (val===undefined ? 0 : val)
     12  *     this.left = (left===undefined ? null : left)
     13  *     this.right = (right===undefined ? null : right)
     14  * }
     15  */
     16 /**
     17  * @param {TreeNode} root
     18  * @return {TreeNode}
     19  */
     20 var invertTree = function(root) {
     21     if(root == null){
     22         return root;
     23     }
     24 
     25 
     26     let queue = [];
     27     queue.unshift(root);
     28     while(queue.length != 0){
     29         let length = queue.length;
     30         for(let i = 0 ; i < length ; ++i){
     31             let current = queue.pop();
     32             let left = null;
     33             let right = null;
     34             if(current.left != null){
     35                 left = current.left;
     36             }
     37             if(current.right != null){
     38                 right = current.right;
     39             }
     40             
     41             current.left = right;
     42             current.right = left;
     43             if(left != null){
     44                 queue.unshift(left);
     45             }
     46             if(right != null){
     47                 queue.unshift(right);
     48             }
     49         }
     50     }
     51     return root;
     52 };