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

Populating Next Right Pointers in Each Node ---LeetCode

2016-11-29 22:11 302 查看
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/

解题思路:

观察可以发现,每一层从左至右每一个节点依次指向它右边的节点。因此可以用层序遍历 Binary Tree Level Order Traversal 来解决这道题,在遍历到这一层的时候,判断它是不是本层最右的元素,如果不是就指向旁边的元素,如果是就指向 null。

在层序遍历中,我们维护一个队列来依次将本层元素入列。那么要如何判断本层元素所处的位置呢?因此可以再维护一个队列,里面装载着层数信息。

所以这道题用两个队列解决,应该是最直接的解法。一个装载节点,一个装载层数信息。

/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
*     int val;
*     TreeLinkNode left, right, next;
*     TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
public void connect(TreeLinkNode root) {
if (root == null) return ;

Queue<TreeLinkNode> nodeQ = new LinkedList<>();
Queue<Integer> depthQ = new LinkedList<>();

if (root != null) {
nodeQ.offer(root);
depthQ.offer(1);
}

while (!nodeQ.isEmpty()) {
TreeLinkNode node = nodeQ.poll();
int depth = depthQ.poll();

if (depthQ.isEmpty()) {
node.next = null;
} else if (depthQ.peek() > depth) {
node.next = null;
} else {
node.next = nodeQ.peek();
}

if (node.left != null) {
nodeQ.offer(node.left);
depthQ.offer(depth + 1);
}
if (node.right != null) {
nodeQ.offer(node.right);
depthQ.offer(depth + 1);
}
}
}
}


另外一种在 Program Creek 里学到的解法:可以不用队列。仅仅维护四个指针,其中两个指针指向两层的第一个节点,另外两个节点用于遍历层。

/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
*     int val;
*     TreeLinkNode left, right, next;
*     TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
public void connect(TreeLinkNode root) {
if (root == null) return ;

TreeLinkNode lastHead = root; // previous level's head
TreeLinkNode lastCurr = null; // previous level's pointer
TreeLinkNode currHead = null; // current level's head
TreeLinkNode current  = null; // current level's pointer

while (lastHead != null) {
lastCurr = lastHead;

while (lastCurr != null) {
if (currHead == null) {
currHead = lastCurr.left;
current  = lastCurr.left;
} else {
current.next = lastCurr.left;
current = current.next;
}

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