LeetCode 117. Populating Next Right Pointers in Each Node 2

follow up of LC116. we used to have a full binary tree but not now we don’t have.

我们之前是只用两个指针 现在用三个指针.

class Solution {
    public Node connect(Node root) {
        Node head = null;
        Node pre = null;
        Node cur = root;
        while(cur != null){
            while(cur != null){
                if(cur.left != null){
                    if(pre == null){
                        head = cur.left;
                    } else {
                        pre.next = cur.left;
                    }
                    pre = cur.left;
                }
                if(cur.right != null){
                    if(pre == null){
                        head = cur.right;
                    } else{
                        pre.next = cur.right;              
                    }
                    pre = cur.right;
                }
                cur = cur.next;
            }
            cur = head;
            head = null;
            pre = null;
        }
        return root;
    }
    
}
posted @ 2020-11-19 04:08  EvanMeetTheWorld  阅读(19)  评论(0)    收藏  举报