Tuesday, February 25, 2014

Given a BST, replace each node with the sum of the values of all the nodes that are greater than that node.

public static int chSum(TNode node){
        if(node == null){
            return 0;
        }else if(node.left == null && node.right == null){
            return 0;  // return 0,since we dont have anything left
        }else{
            int  tmp = node.value;
            node.value = chSum(node.right);
            return tmp + node.value + chSum(node.left);
        }
    }

Flatten an iterator of iterators in Python. If the input is [ [1,2], [3,[4,5]], 6], it should return [1,2,3,4,5,6].

__author__ = 'nitin'

def return_list(a_list):
    i=0
    result_list=[]
    tmp_len=len(a_list)
    while tmp_len>0:
        if type(a_list[i]) is list:
            tmp_list=return_list(a_list[i])
            for j in tmp_list:
                result_list.append(j)
        else:
            result_list.append(a_list[i])
        tmp_len=tmp_len -1
        i=i+1
    return result_list

def iter_of_iterators():
    len_of_list=len(given_list)
    result_list=[]
    i=0
    while len_of_list>0:
        tmp=given_list[i]
        if type(tmp) is list:
            tmp_list=return_list(tmp)
            for j in tmp_list:
                result_list.append(j)
        else:
            result_list.append(given_list[i])
        i=i+1
        len_of_list=len_of_list -1
    return result_list

if __name__=="__main__":
    given_list=[[1,2],[3,[4,5]],6]
    print iter_of_iterators()

My Profile

My photo
can be reached at 09916017317