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

Populating Next Right Pointers in Each Node II ---LeetCode

2016-11-30 13:59 477 查看
https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/

解题思路:

Populating Next Right Pointers in Each Node 这题类似,只是将题目要求任意化,不再局限为仅仅给一棵左右子树高度相等的二叉树。这时我们需要多判断一下它是否具有左右子节点即可。

/**
* 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;
TreeLinkNode lastCurr = null;
TreeLinkNode currHead = null;
TreeLinkNode current  = null;

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

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