0
点赞
收藏
分享

微信扫一扫

填充每个节点的下一个右侧节点指针 leetcode 30

Hyggelook 2022-02-16 阅读 57

 

 

class Solution {
    public Node connect(Node root) {

        if(root == null){
            return root;
        }
        Node pre = root;
        while(pre != null){     //第一层循环决定当前是在那一层进行操作
            Node  tem = pre;    
            while(tem !=null){  //第二层循环决定当前是对哪一个结点的子节点进行操作
                if(tem.left == null){   //代表下一层为空,没有节点了
                    return root;
                }
                tem.left.next =tem.right;//连接当前结点的左右节点

                if(tem.next != null){   //当前结点有next结点,所以要把该节点的右孩子的next、指向该节点的next的结点的左孩子
                    tem.right.next = tem.next.left;
                }
                tem = tem.next;         //tem指向这一层的下一个结点

            }

            pre =pre.left;  //每次都从下一层的最左边开始
        }

        return root;


    }
}
举报

相关推荐

0 条评论