116. 填充每個節點的下一個右側節點指針
問題
給定一個完美二叉樹,其所有葉子節點都在同一層,每個父節點都有兩個子節點。二叉樹定義如下:
填充它的每個 next 指針,讓這個指針指向其下一個右側節點。如果找不到下一個右側節點,則將 next 指針設置爲 NULL。
初始狀態下,所有 next 指針都被設置爲 NULL。
例子
思路
完美二叉樹:除了葉子結點之外的每一個結點都有兩個孩子結點
-
方法1
-
方法2
117. 填充每個節點的下一個右側節點指針 II
問題
不是完美二叉樹
代碼
//方法1
class Solution {
public Node connect(Node root) {
if(root==null) return root;
Queue<Node> q = new LinkedList<>();
q.offer(root);
Node pre=null,node=null;
while(q.size()>0) {
int len = q.size();
//獲取該層第一個結點pre,.next=node
pre = q.poll();
if(pre.left!=null) q.offer(pre.left);
if(pre.right!=null) q.offer(pre.right);
for(int i=1; i<len; i++) {
node =q.poll();
if(node.left!=null) q.offer(node.left);
if(node.right!=null) q.offer(node.right);
pre.next = node;
pre=node;
}
//最後一個結點.next=null
pre.next=null;
}
return root;
}
}
//方法2