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

LeetCode: Populating Next Right Pointers in Each Node II 解题报告

2014-10-21 19:20 477 查看
[b]Populating Next Right Pointers in Each Node II[/b]
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

[b]SOLUTION 1[/b]

本题还是可以用Level Traversal 轻松解出,连代码都可以跟上一个题目一模一样。Populating Next Right Pointers in Each Node Total

但是不符合空间复杂度的要求:constant extra space.

时间复杂度: O(N)

// SOLUTION 1: Iteration
public void connect1(TreeLinkNode root) {
if (root == null) {
return;
}

TreeLinkNode leftEnd = root;

// Bug 1: don't need " && leftEnd.left != null"
while (leftEnd != null) {
TreeLinkNode cur = leftEnd;

TreeLinkNode dummy = new TreeLinkNode(0);
TreeLinkNode pre = dummy;
while (cur != null) {
if (cur.left != null) {
pre.next = cur.left;
pre = cur.left;
}

if (cur.right != null) {
pre.next = cur.right;
pre = cur.right;
}

cur = cur.next;
}
leftEnd = dummy.next;
}
}


View Code

[b]CODE ON GITHUB:
[/b]

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/tree/Connect2_2014_1229.java

Connect2.java
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: