Monday, October 31, 2011

把BT 同一层的sibling 连起来,constant 内存

struct Node {
    int value;
    Node *left;
    Node *right;
    Node *sibling; 
};


//把BT 同一层的sibling 连起来,constant 内存.
//
//                  1  -->null
//               /     \
//              2   -->  3  -->null
//            /       /    \
//          7     --> 8   -> 4  -->null
//
//
//开始没要求constant, 用queue记录每层的结点 O(n)即可. 后来要求constant,在提示下才搞定。
//先让不知道答案的xdjm想想吧。回头贴我的做法。
void connect_sibling( Node *root ) {
    root->sibling = null;
    Node *cur, *dummy;
    dummy = new Node;

    while( root ) {  //dummy->slibling是指向上次下一层的最左节点。
        cur = dummy;  //这样保证dummy->slibling总指向最左节点
        while( root ) {   // 找上一层的最右边节点, 假设当前层sibling已连好。

            if( root->left ) {
                cur->sibling = root->left;
                cur = root->left;
            }

            if(root->right){
                cur->sibling = root->right;
                cur = root->right;
            }

            root = root->sibling; //上一层的下一个姐妹,直到最右边。
        } //end of while second loop
        //此时,下一层已串好。

        cur->sibling = null; //最右边下一层填空。
        root = dummy->sibling; //上层的右一个节点。
    }
    delete dummy;
}

No comments: