[LeetCode]Populating Next Right Pointers in Each Node II

来源:互联网 发布:tuneskit for windows 编辑:程序博客网 时间:2024/06/07 09:27

Question

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

本题难度Hard。

层次递进法

【复杂度】
时间 O(2^h-1) 空间 O(1)

【思路】
本题与[LeetCode]Populating Next Right Pointers in Each Node不一样的地方在于节点可以少儿子或没儿子。还是利用父节点层来链接子节点层,链接子节点时利用cur代表需要链接的节点。在这里需要用一点技巧,就是用fake来处理子节点层的第一个节点。如下图,last指向的是父节点层的节点。

last    1 -> NULL     \ /  \      2 -> 3 -> NULL     父节点层       \    \ fake-> 4 -> 5 -> NULL   子节点层             |            cur

【代码】

public class Solution {    public void connect(TreeLinkNode root) {        //require        TreeLinkNode last=root;        //invariant        while(last!=null){            TreeLinkNode fake=new TreeLinkNode(0);            TreeLinkNode cur=fake;            //遍历父节点层            while(last!=null){                // 尝试链接左节点                if(last.left!=null){                    cur.next=last.left;                    cur=cur.next;                }                // 尝试链接右节点                if(last.right!=null){                    cur.next=last.right;                    cur=cur.next;                }                last=last.next;            }            // 遍历完后,将last移动到子节点层的第一个,准备链接下一层            last=fake.next;        }    }}

参考

[Leetcode] Populating Next Right Pointers in Each Node 二叉树Next指针

0 0
原创粉丝点击