117. Populating Next Right Pointers in Each Node II

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

 

这道题是要将一棵树的每一层维护成一个链表,树本身是给定的。其实思路上很接近层序遍历Binary Tree Level Order Traversal,只是这里不需要额外维护一个队列。因为这里每一层我们会维护成一个链表,这个链表其实就是每层起始的那个队列,因此我们只需要维护一个链表的起始指针就可以依次得到整个队列了。接下来就是有左加左入链表,有右加右入链表,知道链表没有元素了说明到达最底层了。算法的复杂度仍然是对每个结点访问一次,所以是O(n),而空间上因为不需要额外空间来存储队列了,所以是O(1)。

维护层链表所需要: 首节点--也是下层的父节点开始节点, 临时节点用来链接链表向右

维护多个层链表需要: 临时节点(上层的head) 用来开始下层链表

代码如下: 

public void connect(TreeLinkNode root) {

        public void connect(TreeLinkNode root) {
        if (root == null) return;
        TreeLinkNode temp = null;// 本层实现遍历的中介点
        TreeLinkNode head = null;// 记住本层的头节点, 下次作为是否开启内循环的判断和内循环的开始点
        TreeLinkNode cur = root;// 上一层的遍历点
        while (cur != null) {
           // 内循环遍历上一层的节点
            while (cur != null) {
                // 分情况看节点是否存在
                if (cur.left != null) {
                    // 本层节点的遍历节点是否存在
                    if (temp != null) {  
                        temp.next = cur.left;
                    } else {
                        //不存在的话先保存头结点
                        head = cur.left;
                    }
                    //遍历的传递
                    temp = cur.left;
                }
                
                if (cur.right != null) {
                    if (temp !=  null) {
                        temp.next = cur.right;
                    } else {
                        head = cur.right;
                    }
                    temp = cur.right;
                }
                // 上层遍历的传递
                cur = cur.next;
            }
            //开启下层循环, 重置下层的头结点和遍历节点
            cur = head;
            temp = null;
            head = null;
            
        }
}

  

这道题是树的层序遍历Binary Tree Level Order Traversal的扩展,操作上会更加繁琐一些,因为是通过维护层链表来完成遍历,不过本质上还是一次广度优先搜索。

以上是关于117. Populating Next Right Pointers in Each Node II的主要内容,如果未能解决你的问题,请参考以下文章

117. Populating Next Right Pointers in Each Node II

117. Populating Next Right Pointers in Each Node II

117. Populating Next Right Pointers in Each Node II

117. Populating Next Right Pointers in Each Node II

117. Populating Next Right Pointers in Each Node II

117. Populating Next Right Pointers in Each Node II