populating-next-right-pointers-in-each-node

来源:互联网 发布:什么是淘宝订购参谋 编辑:程序博客网 时间:2024/06/05 17:30

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


题目的意思很清楚,树的每一层最右边的节点next域null,其余的结点左边节点next域指向右边结点,并且所给树一定是完美二叉树。

import java.util.LinkedList;public class Solution {    public void connect(TreeLinkNode root) {        if(root == null) return;        LinkedList list = new LinkedList();        list.offer(root);        while(!list.isEmpty()) {            int size = list.size();            for(int i=0; i<size; i++) {                TreeLinkNode curNode = (TreeLinkNode)list.poll();                if(i == size-1) {                    curNode.next = null;                } else {                    curNode.next = (TreeLinkNode)list.peek();                }                if(curNode.left != null) list.offer(curNode.left);                if(curNode.right != null) list.offer(curNode.right);            }        }    }}

这里用到LinkedList集合,实际上当成了队列来使用,注意LinkedList两个方法poll()和peek()的区别,使用poll()方法时,获取并移除此列表的头,使用peek()方法时,获取但不移除此列表的头。