Populating Next Right Pointers in Each Node leetcode java

愛做飯的小瑩子發表於2014-08-02

題目

 

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就指向右孩子。如果當前節點有右孩子,那麼判斷,如果當前節點的next是null,
說明當前節點已經到了最右邊,那麼右孩子也是最右邊的,所以右孩子指向null。如果當前節點的next不是null,那麼當前節點的右孩子的next就需要
指向當前節點next的左孩子。
遞迴求解就好。

程式碼如下:
 1     public void connect(TreeLinkNode root) {
 2         if(root==null)
 3             return;
 4         if(root.left!=null)
 5             root.left.next=root.right;
 6         if(root.right!=null){
 7             if(root.next!=null)
 8                 root.right.next = root.next.left;
 9             else
10                 root.right.next = null;
11         }
12         connect(root.left);
13         connect(root.right);
14     }

相關文章