Populating Next Right Pointers in Each Node

来源:互联网 发布:人工智能 图书馆 编辑:程序博客网 时间:2024/06/06 16:53

1.题目

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.

2.算法



   public void connect(TreeLinkNode root) {          if(root == null)              return;          TreeLinkNode lastHead = root;          TreeLinkNode current = null;          TreeLinkNode curHead = null;          while(lastHead!=null)          {              TreeLinkNode lastCur = lastHead;              while(lastCur != null)              {                  if(lastCur.left!=null)                  {                      if(curHead == null)                      {                          curHead = lastCur.left;                          current = curHead;                      }                      else                      {                          current.next = lastCur.left;                          current = current.next;                      }                  }                  if(lastCur.right!=null)                  {                      if(curHead == null)                      {                          curHead = lastCur.right;                          current = curHead;                      }                      else                      {                          current.next = lastCur.right;                          current = current.next;                      }                  }                                  lastCur = lastCur.next;                    }              lastHead = curHead;              curHead = null;          }      }  


0 0
原创粉丝点击