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 这题类似,只是将题目要求任意化,不再局限为仅仅给一棵左右子树高度相等的二叉树。这时我们需要多判断一下它是否具有左右子节点即可。
解题思路:
和 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; } } }
相关文章推荐
- [LeetCode 116 117] - 填充每一个节点的指向右边邻居的指针I & II (Populating Next Right Pointers in Each Node I & II)
- LeetCode Populating Next Right Pointers in Each Node II
- LeetCode(Oct28'12):Populating Next Right Pointers in Each Node II
- leetcode 79: Populating Next Right Pointers in Each Node II
- 【leetcode】Populating Next Right Pointers in Each Node II
- LeetCode-Populating Next Right Pointers in Each Node II
- leetcode_question_117 Populating Next Right Pointers in Each Node II
- [LeetCode] Populating Next Right Pointers in Each Node II
- LeetCode-Populating Next Right Pointers in Each Node II
- [leetcode刷题系列]Populating Next Right Pointers in Each Node II
- LeetCode: Populating Next Right Pointers in Each Node II
- leetcode--Populating Next Right Pointers in Each Node II
- LeetCode | Populating Next Right Pointers in Each Node II
- LeetCode - Populating Next Right Pointers in Each Node II
- LeetCode_Populating Next Right Pointers in Each Node II
- leetcode -- Populating Next Right Pointers in Each Node II
- [leetcode] Populating Next Right Pointers in Each Node II
- Leetcode_Populating Next Right Pointers in Each Node II
- [Leetcode] Populating Next Right Pointers in Each Node ii
- [leetcode]Populating Next Right Pointers in Each Node II