1. 程式人生 > >樹——populating-next-right-pointers-in-each-node(填充每個節點的next指針)

樹——populating-next-right-pointers-in-each-node(填充每個節點的next指針)

ive parent it is fec pre evel populate reel tro

問題

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 toNULL.

Initially, all next pointers are set toNULL.

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

思路

首先判斷根節點是否為null,如果是,return;如果不是,繼續。

設置節點node,用來指向每層的第一個節點;設置節點next,用來指向該層的每個節點。

當node的左孩子存在時,使用next來遍歷該層的其它節點:

  (1)讓node左孩子的next指向node右孩子;

  (2)若next.next不為null,讓node右孩子的next指向next.next的左孩子。

代碼

 1 /**
 2  * Definition for binary tree with next pointer.
 3  * public class TreeLinkNode {
 4  *     int val;
 5  *     TreeLinkNode left, right, next;
 6  *     TreeLinkNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public void connect(TreeLinkNode root) {
11         if(root==null)
12             return;
13         root.next = null;
14         TreeLinkNode node = root, next = node;
15         while(node.left!=null){
16             next = node;
17             while(next!=null){
18                 next.left.next = next.right;
19                 if(next.next!=null)
20                     next.right.next = next.next.left;
21                 next = next.next;
22             }
23             node = node.left;
24         }
25     }
26 }

樹——populating-next-right-pointers-in-each-node(填充每個節點的next指針)