# 【Leetcode】Populating Next Right Pointers in Each Node

323人阅读 评论(0)

Given a binary tree

    struct TreeLinkNode {
}


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

	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;
}


	public void connect(TreeLinkNode root) {
if(null==root)
return;
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; //处理下一层
}
}

个人资料
等级：
访问量： 57万+
积分： 8679
排名： 2734
博客专栏
 Leetcode题解java版 文章：289篇 阅读：494376
最新评论