本文主要是介绍LeetCode 117 Populating Next Right Pointers in Each Node II (链表 层次遍历 推荐),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
- You may only use constant extra space.
For example,
Given the following binary tree,
1/ \2 3/ \ \4 5 7
After calling your function, the tree should look like:
1 -> NULL/ \2 -> 3 -> NULL/ \ \4-> 5 -> 7 -> NULL
题目分析:和Populating Next Right Pointers in Each Node那题比本题不保证是满二叉树,因此如果用那题的做法将会非常麻烦,需要判断很多null的情况,换个角度思考,模拟一下树层次遍历的过程,给每一层加一个头结点,就可以解决这个问题。1ms
/*** 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) {TreeLinkNode lastNode = root;while (lastNode != null) {TreeLinkNode cur = new TreeLinkNode(0);TreeLinkNode curHead = cur;while (lastNode != null) {if (lastNode.left != null) {cur.next = lastNode.left;cur = cur.next;}if (lastNode.right != null) {cur.next = lastNode.right;cur = cur.next;}lastNode = lastNode.next;}lastNode = curHead.next;}}
}
这篇关于LeetCode 117 Populating Next Right Pointers in Each Node II (链表 层次遍历 推荐)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!