Given a binary tree
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *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
.
Note:
- You may only use constant extra space.
- You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
Given the following perfect binary tree,
1 / \ 2 3 / \ / \ 4 5 6 7
After calling your function, the tree should look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL
JAVA:
(easy)
public void connect(TreeLinkNode root) {
if(root == null)
return;
if(root.left != null){
root.left.next = root.right;
if(root.next != null)
root.right.next = root.next.left;
}
connect(root.left);
connect(root.right);
}
(hard)
java:
class TreeNode{
int val;
TreeNode left=null;
TreeNode right=null;
void TreeNode(int val){
this.val=val;
}
}
class TreeLinkNode{
int val;
TreeLinkNode left=null;
TreeLinkNode right=null;
TreeLinkNode next=null;
void TreeLinkNode(int val){
this.val=val;
}
}
public class Solution{
public TreeLinkList reslove(TreeNode root){
List<List<TreeNode>> list=new ArrayList<List<TreeNode>>();
Queue<TreeNode> queue=new LinkedList<TreeNode>();
if(root==null) return null;
queue.offer(root);
while(!queue.isEmpty){
List<TreeNode> subList=new ArrayList<TreeNode>();
int queuesize=queue.size();
for(int i=0;i<queuesize;i++){
if(queue[i].left!=null){
queue.offer(queue.peer().left);
}
if(queue[i].right!=null){
queue.offer(queue.peer().right);
}
subList.add(queue.poll());
}
list.add(subList);
}
for(int i=0;i<list.length,i++){
if(list[i].length>1){
for(int j=1;j<list[i].length;j++){
list[j-1].next=list[j];
}
list[list[i].length-1].next=null;
}
else{
list[i].next=null;
}
}
return list[0][0];
}
}
python:
#coding:utf-8
class TreeLinkNode:
def __init__(self,val,left,right,next1):
self.val=val
self.left=left
self.right=right
self.next1=next1
class Solution:
def resolve(self,root):
if not root:
return None
cur=root
next=root.left
while cur.left is not None:
cur.left.next=cur.right
if cur.next is not None:
cur.right.next=cur.next.left
cur=cur.next
else:
cur=next
next=cur.left