Javascript Preorder solution


  • 0
    M
    var rightSideView = function(root) {
        var res = [],i = 0;
        function preOrderWrap(node,i){
            var index = i;
            var preOrder = function(n){
                if(n){
                    res[index++] = n.val;
                    preOrderWrap(node.left, index);
                    preOrderWrap(node.right, index);
                }  
            }
            preOrder(node ,i)
        }
      preOrderWrap(root,0);
      return res;
    };
    

    There is another Solution,Their time complexity is same (O(n)),but the following solution is much more better.

    var rightSideView = function(root) {
        var res = [],  Q = [] ,i ,len, rt;
        if(root)  Q.push(root);
        while(Q.length>0){
            len = Q.length;
            for(i = 0; i < len ;i++){
                rt = Q.shift();
                if( i ==0) res.push(rt.val);
                if(rt.right) Q.push(rt.right);
                if(rt.left) Q.push(rt.left);
            }
        }
        return res;
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.