您的位置:首页 > Web前端 > Node.js

[leet code] Populating Next Right Pointers in Each Node II

2014-01-19 08:25 489 查看
Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

You may only use constant extra space.

For example,

Given the following binary tree,

1
/  \
2    3
/ \    \
4   5    7


After calling your function, the tree should look like:

1 -> NULL
/  \
2 -> 3 -> NULL
/ \    \
4-> 5 -> 7 -> NULL

============
Analysis:

1. Recursive approach

2. Each recursive call focus on one node

Accordingly, we here are different cases while handling one node:

For left child (if left child exist):

left child -> right child, if right child exist

left child -> null, if current node is the right most node && no right child

left child -> next available node in the same level

left child -> null if no next node available in the sam level

For right child(if right child exist):

right child -> null if current node is the right most node

right child -> next available node in the same level

right child -> null if no next node available in the same level

!!! Note that during recursive call, we must deal with right child then left child. Otherwise, the "next" links of the nodes on the right hand side of the same level would not have been established when program finding the next available node in the same
level.

/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
*     int val;
*     TreeLinkNode left, right, next;
*     TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
public void connect(TreeLinkNode root) {
if (root == null) return;
root.next = null;

helper(root);
return;
}

public void helper(TreeLinkNode node){
if (node == null) return;

// handle left child
if (node.left != null){
if (node.right != null) node.left.next = node.right;
else{ // has left child no right child
if (node.next != null){
TreeLinkNode temp = node.next;
while(temp.next != null && temp.left == null && temp.right == null) temp = temp.next;
if (temp.left != null){
node.left.next = temp.left;
}else if(temp.right != null){
node.left.next = temp.right;
}else {
node.left.next = null;
}
}
else node.left.next = null;
}
}

// handle right child
if (node.right != null){
if (node.next != null){
TreeLinkNode temp = node.next;
while(temp.next != null && temp.left == null && temp.right == null) temp = temp.next;

if (temp.left != null){
node.right.next = temp.left;
}else if(temp.right != null){
node.right.next = temp.right;
}else {
node.right.next = null;
}
}
else node.right.next = null;
}

helper(node.right); // !!! must right first
helper(node.left);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: