填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
示例 1:
输入:root = [1,2,3,4,5,6,7]
输出:[1,#,2,3,#,4,5,6,7,#]
解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。序列化的输出按层序遍历排列,同一层节点由 next 指针连接,'#' 标志着每一层的结束。
/*// 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; }};*/classSolution{publicNodeconnect(Noderoot){if(root==null){returnroot;}Deque<Node>q=newArrayDeque<>();q.offer(root);while(!q.isEmpty()){Nodep=null;for(intn=q.size();n>0;--n){Nodenode=q.poll();if(p!=null){p.next=node;}p=node;if(node.left!=null){q.offer(node.left);}if(node.right!=null){q.offer(node.right);}}}returnroot;}}
/** * Definition for a Node. * type Node struct { * Val int * Left *Node * Right *Node * Next *Node * } */funcconnect(root*Node)*Node{ifroot==nil{returnroot}q:=[]*Node{root}forlen(q)>0{varp*Nodeforn:=len(q);n>0;n--{node:=q[0]q=q[1:]ifp!=nil{p.Next=node}p=nodeifnode.Left!=nil{q=append(q,node.Left)}ifnode.Right!=nil{q=append(q,node.Right)}}}returnroot}
/*// 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; }};*/classSolution{publicNodeconnect(Noderoot){if(root!=null){dfs(root.left,root.right);}returnroot;}privatevoiddfs(Nodeleft,Noderight){if(left==null||right==null){return;}left.next=right;dfs(left.left,left.right);dfs(left.right,right.left);dfs(right.left,right.right);}}
/** * Definition for a Node. * type Node struct { * Val int * Left *Node * Right *Node * Next *Node * } */funcconnect(root*Node)*Node{vardfsfunc(*Node,*Node)dfs=func(left,right*Node){ifleft==nil||right==nil{return}left.Next=rightdfs(left.Left,left.Right)dfs(left.Right,right.Left)dfs(right.Left,right.Right)}ifroot!=nil{dfs(root.Left,root.Right)}returnroot}