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

Leetcode_116_Populating Next Right Pointers in Each Node

2015-02-05 19:18 429 查看
本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/43532817

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)题意为给定一颗二叉树(可以当做满二叉树),将其每层上的节点从左到右链接起来形成链表。

(2)本文主要使用队列来实现。大体思路为:从根节点开始,按从树根向下的顺序依次将每层的节点存入队列中。首先,将根节点存入队列中,只要队列不为空,就让队头元素出队,然后判断该元素是否有左右孩子,如果有分别将左右孩子加入队列中;然后,二叉树是满二叉树,所以可以求出每层的节点数目,依次为1,2,4,8,....,通过临时变量记录当前的层次level,通过Math.power(2, level),求得当前层上的节点数levelcount,还需要使用变量count记录当前层次上遍历了多少节点,这样每当遍历的节点数和levelcount相同时,说明当前层已遍历到最后一个节点,将该节点的next置为null,继续进行下一层的遍历。由于每次出队的总是第一个元素,所以只需将出队后的元素next置为当前队列第一个元素即可;循环遍历,直到所有节点进队列、出队列为止,最后所得即为结果。

(3)该题的思路和“按层次遍历二叉树”类似,感兴趣可以参照“按层次输出二叉树”。只不过本文所示算法效率不是很高,但是比较容易理解吧。

(4)希望本文对你有所帮助。

算法代码实现如下:

/**
*
* @author liqq
*/
public static void connect(TreeLinkNode root) {
if(root ==null) return ;
if(root!=null&&root.left==null&&root.right==null) root.next=null;

List<TreeLinkNode> list = new LinkedList<TreeLinkNode>();
list.add(root);
int count = 0;
int level = 0;
int levelcount = 1;
while(list.size()!=0){
TreeLinkNode fis = list.remove(0);
count++;
if(list.size()>=0 && count!=levelcount){
TreeLinkNode sec = list.get(0);
fis.next = sec;
}else{
fis.next =null;
level++;
levelcount = (int) Math.pow(2, level);
count=0;
}

if(fis.left!=null){
list.add(fis.left);
}

if(fis.right!=null){
list.add(fis.right);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: