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

LeetCode Populating Next Right Pointers in Each Node II

2015-09-10 04:52 691 查看
原题链接在这里:https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/

题目:

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

题解:

Populating Next Right Pointers in Each Node的进阶版。

next是要连接的下一个点,通过rootNext找到. rootNext 初始化为root.next, 若是rootNext.left 不为null, next更新为rootNext.left, 即可break; 若是rootNext.right 不为null, next更新为rootNext.right, 即可break. 否则rootNext就一直往当前rootNext.next方向更新。

Note:1. 递归时先递归右子树,后递归左子树,因为右边的搞定了,左边才知道指向哪里。

2. while loop中找到next后要加break, 否则就会一直找下去,因为rootNext没有更新.

Time Complexity: O(n), 每个点访问不会超过两次. Space: O(logn), 用了logn层stack.

Time Complexity: O(n). Space: O(logn).

AC Java:

/**
* 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;
}
TreeLinkNode next = null;
TreeLinkNode rootNext = root.next;
while(rootNext != null){
if(rootNext.left != null){
next = rootNext.left;
break;
}else if(rootNext.right != null){
next = rootNext.right;
break;
}else{
rootNext = rootNext.next;
}
}
if(root.right != null){
root.right.next = next;
}
if(root.left != null){
if(root.right != null){
root.left.next = root.right;
}else{
root.left.next = next;
}
}
connect(root.right);
connect(root.left);
}
}


Iteration 版本.

Time Complexity: O(n). Space: O(1).

/**
* 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) {
TreeLinkNode head = root;
while(head != null){
TreeLinkNode nextDummy = new TreeLinkNode(0); //记录下一层的假头
TreeLinkNode cur = nextDummy;
while(head != null){
if(head.left != null){
cur.next = head.left;
cur = cur.next;
}
if(head.right != null){
cur.next = head.right;
cur = cur.next;
}
head = head.next;
}
head = nextDummy.next; //head 更新到下一层假头的next上面
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: