LeetCode Populating Next Right Pointers in Each Node II

捕获.PNG
void connect(TreeLinkNode *root) {
        TreeLinkNode* dummy = new TreeLinkNode(0);
        while(root){
            TreeLinkNode* tmp = dummy;
            while(root){
                if(root -> left){
                    tmp -> next = root -> left;
                    tmp = tmp -> next;
                }
                if(root -> right){
                    tmp -> next = root -> right;
                    tmp = tmp -> next;
                }
                root = root -> next;
            }
            root = dummy -> next;
            dummy -> next = NULL;
        }
    }

加入一个dummy可以标识下一层的第一个结点位置,而且简化了判断条件。

你可能感兴趣的:(LeetCode Populating Next Right Pointers in Each Node II)