116. Populating Next Right Pointers in Each Node
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
struct Node { int val; Node *left; Node *right; Node *next; }
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL
.
Initially, all next pointers are set to NULL
.
Example:
网上找到比较好的讲解是来自 https://segmentfault.com/a/1190000003465911
1. 先来递归的
思路
由于父节点多了next指针,我们不用记录父节点的父节点就能直到它相邻的节点。对于左子节点来说,其next节点就是父节点的右节点。对于右子节点来说i,其next节点就是父节点的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,Node _left,Node _right,Node _next) { val = _val; left = _left; right = _right; next = _next; } }; */ class Solution { public Node connect(Node root) { Node level_start=root; while(level_start!=null){ Node cur=level_start; while(cur!=null){ if(cur.left!=null) cur.left.next=cur.right; if(cur.right!=null && cur.next!=null) cur.right.next=cur.next.left; cur=cur.next; } level_start=level_start.left; } return root; } }
2. iterative solution
class Solution { public Node connect(Node root) { if(root == null) return null; Queue<Node> q = new LinkedList(); q.offer(root); while(!q.isEmpty()) { int size = q.size(); for(int i = 0; i < size; i++) { Node cur = q.poll(); if(i < size - 1) { cur.next = q.peek(); } if(cur.left != null) q.add(cur.left); if(cur.right != null) q.add(cur.right); } } return root; } }
本质很简单,就像level order,把每一层的node放到queue中,然后遍历所有的node,当前index到size-1就不用执行next操作了,因为最右边的node.next = null,每次pop出来当前的cur,然后cur.next = q.peek(),操作完成后把它的左右子节点加进去。