LeetCode 116. Populating Next Right Pointers in Each Node

LeetCode 116. Populating Next Right Pointers in Each Node_第1张图片

前提:是完美二叉树 

用层次遍历的方法,但是因为上一层已经有了next节点,所以就不需要队列来维护顺序,直接判断next是否为空和父子节点的关系,就能确定下一个节点的位置

复杂度为O(n)

/*
// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {}
    
    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
*/

class Solution {
    public Node connect(Node root) {
        if(root == null)
            return root;
        if(root.left == null)
            return root;
        Node pre = root;
        Node cur = root.left;
        Node first = root;
        int level = 1;
        while(first.left != null){
            if(cur == pre.left){
                cur.next = pre.right;
                cur = cur.next;
            }else if(cur == pre.right){
                if(pre.next != null){
                    pre = pre.next;
                    cur.next = pre.left;
                    cur = cur.next;
                }else{
                    level++;
                    pre = first.left;
                    cur = pre.left;
                    first = pre;
                }
            }
        }
        return root;
    }
}

你可能感兴趣的:(Leetcode刷题,leetcode)