题目链接:https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
题目:
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).
For example,
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
思路:
1、层次遍历,保存每层结点。然后处理各层结点指针。时间复杂度为O(n),空间复杂度为O(n)。
2、因为是题设是满二叉树,所以我们可以从上而下的从最左边开始对每层处理next。具体思路参考 http://www.cnblogs.com/felixfang/p/3647898.html
时间复杂度为O(n),空间复杂度为O(1)。
算法:
public void connect(TreeLinkNode root) {
List<List<TreeLinkNode>> lists = levelOrder(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;
}
}
/**
* 统计每层节点
*/
public List<List<TreeLinkNode>> levelOrder(TreeLinkNode root) {
int height = heightTree(root);
List<List<TreeLinkNode>> lists = new ArrayList<List<TreeLinkNode>>();
for (int i = 1; i <= height; i++) {
List<TreeLinkNode> list = new ArrayList<TreeLinkNode>();
list = kLevelNumber(root, 1, list, i);
lists.add(list);
}
return lists;
}
/***
* kk是目标层数,height是当前遍历结点高度
*/
public List<TreeLinkNode> kLevelNumber(TreeLinkNode p, int height, List<TreeLinkNode> list, int kk) {
if (p != null) {
if (height == kk) {
list.add(p);
}
list = kLevelNumber(p.left, height + 1, list, kk);
list = kLevelNumber(p.right, height + 1, list, kk);
}
return list;
}
public int heightTree(TreeLinkNode p) {
if (p == null)
return 0;
int h1 = heightTree(p.left);
int h2 = heightTree(p.right);
return h1 > h2 ? h1 + 1 : h2 + 1;
}
public void connect(TreeLinkNode root) {
if(null==root)
return;
TreeLinkNode curLev = null;
while(root.left!=null){ //从最左结点开始处理每一层
curLev = root; //当前层
while(curLev!=null){//向右边处理
curLev.left.next = curLev.right; //本结点的左右子结点相互连接
if(curLev.next!=null){
curLev.right.next = curLev.next.left;//相邻两节点的相邻子结点连接
}
curLev = curLev.next;//处理右边结点
}
root = root.left; //处理下一层
}
}