117Populating Next Right Pointers in Each Node II

来源:互联网 发布:域名注册后怎么建网站 编辑:程序博客网 时间:2024/05/16 19:46

题目链接:https://leetcode.com/problems/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    7After calling your function, the tree should look like:         1 -> NULL       /  \      2 -> 3 -> NULL     / \    \    4-> 5 -> 7 -> NULL

解题思路:
这题和 116 Populating Next Right Pointers in Each Node 的思路一模一样。实际上,我把 116 的答案直接复制到本题轻松 Accepted 。
具体再说一下思路:
1. 层次遍历二叉树,把层次遍历所需的层队列换成层链表,即每层一个链表
2. 在遍历每一层的过程中,通过一个临时指针 p,将该层的结点链接到一起
3. 每一层遍历完后,返回该层左数第一个结点的引用,也就是该层链表的头结点
4. 在上一层给出的结点链表下,遍历下一层的结点,遍历的过程中重复上述操作

代码实现:

/** * 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 oldHead = root;        while(oldHead != null) {            TreeLinkNode p = null;            TreeLinkNode newHead = p; // 二者并不是指向同一个对象的引用            while(oldHead != null) {                if(oldHead.left != null) {                    if(p == null) {                        p = oldHead.left;                        newHead = p; // 二者指向同一个对象的引用                    }                    else {                        p.next = oldHead.left;                        p = p.next;                    }                }                if(oldHead.right != null) {                    if(p == null) {                        p = oldHead.right;                        newHead = p; // 二者指向同一个对象的引用                    }                    else {                        p.next = oldHead.right;                        p = p.next;                    }                }                oldHead = oldHead.next;            }            oldHead = newHead;        }    }}
61 / 61 test cases passed.Status: AcceptedRuntime: 2 ms
0 0
原创粉丝点击