【leetcode】993. 二叉树的堂兄弟节点

 

void visitTree( struct TreeNode * t , struct TreeNode * form , int * x , int * y , int depth ){

    if( t == NULL ){

        return ;

    }

    if( t -> val == *x ){

        *x = form -> val + depth * 1000; 

    }

    //if the value of current node is equaling the value of assigned y, updating y
    if( t -> val == *y ){

        *y = form -> val + depth * 1000; 

    }

    //visitng the left and right child of t
    visitTree( t -> left , t , x , y , depth + 1 );
    visitTree( t -> right , t , x , y , depth + 1 );

}

bool isCousins( struct TreeNode * root , int x , int y ){

    visitTree( root , root , &x , &y , 0 );

    //making sure x and y in the same depth, and making sure they have different parents 
    if( x % 1000 != y % 1000 && x / 1000 == y / 1000 ){

        return true;

    }

    return false;

}

 

posted @ 2020-11-24 11:20  温暖了寂寞  阅读(124)  评论(0编辑  收藏  举报