题目要求

Given a binary tree

    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Note:

You may only use constant extra space.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
     1
   /  \
  2    3
 / \  / \
4  5  6  7

After calling your function, the tree should look like:

     1 -> NULL
   /  \
  2 -> 3 -> NULL
 / \  / \
4->5->6->7 -> NULL

给一个完全二叉树,将当前节点的next值指向其右边的节点。
而在II中则是提供了一个不完全的二叉树,其它需求没有发生改变。
额外的需求包括O(1)的空间复杂度

思路和代码

这里其实是水平遍历(level traversal)的一种实现。我们需要使用一个变量来存储父节点,再使用一个变量来存储当前操作行的,将前一个指针指向当前父节点的子节点。

    public void connect(TreeLinkNode root) {
        TreeLinkNode head = root;
        TreeLinkNode prev = null;
        TreeLinkNode nextHead = null;
        while(head!=null){
            while(head!=null){
                if(head.left!=null){
                    if(prev!=null){
                        prev.next = head.left;
                    }else{
                        nextHead = head.left;
                    }
                    prev = head.left ;
                }
                if(head.right!=null){
                    if(prev!=null){
                        prev.next = head.right;
                    }else{
                        nextHead = head.right;
                    }
                    prev = head.right ;
                }
                head = head.next;
            }
            head = nextHead;
            prev = null;
            nextHead = null;
        }
    }    

clipboard.png
想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注我的微信公众号!将会不定期的发放福利哦~


raledong
2.7k 声望2k 粉丝

心怀远方,负重前行