# 【Leetcode】Populating Next Right Pointers in Each Node II

232人阅读 评论(0)

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


1、用"Populating Next Right Pointers in Each Node".的算法，仍然有效，只是空间复杂度是O(n)

	public void connect(TreeLinkNode root) {
for (List<TreeLinkNode> list : lists) {
for (int i = 0; i < list.size() - 1; i++) {
list.get(i).next = list.get(i + 1);
}
list.get(list.size() - 1).next = null;
}
}

/**
* 统计每层节点
*/
int height = heightTree(root);
for (int i = 1; i <= height; i++) {
list = kLevelNumber(root, 1, list, i);
}
return lists;
}

/***
* kk是目标层数，height是当前遍历结点高度
*/
if (p != null) {
if (height == kk) {
}
list = kLevelNumber(p.left, height + 1, list, kk);
list = kLevelNumber(p.right, height + 1, list, kk);
}
return list;
}

if (p == null)
return 0;
int h1 = heightTree(p.left);
int h2 = heightTree(p.right);
return h1 > h2 ? h1 + 1 : h2 + 1;
}


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：517238次
• 积分：8095
• 等级：
• 排名：第2496名
• 原创：305篇
• 转载：6篇
• 译文：0篇
• 评论：34条
博客专栏
 Leetcode题解java版 文章：289篇 阅读：442226
文章分类
阅读排行
最新评论