Populating Next Right Pointers in Each Node 設定二叉樹的next節點

範長法@三月軟體發表於2014-10-21

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設定為右側相鄰節點。

解決思路:

  一次對每個節點進行遍歷,若左右子樹不為空,則將左子樹的next指向右子樹,若該節點的next為空,則將右子樹的next設定為空(看圖分析)

  若該節點的next不為空,則指向與該節點同層次中相鄰的右側節點的左子樹(看圖分析)

  這裡使用一個佇列,將根節點先放入佇列,從佇列中取出一個節點node,node移除佇列,node子樹的next節點處理按照上面分析操作。

程式碼如下:

 1 /**
 2  * Definition for binary tree with next pointer.
 3  * struct TreeLinkNode {
 4  *  int val;
 5  *  TreeLinkNode *left, *right, *next;
 6  *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     void connect(TreeLinkNode *root) {
12         if(root == NULL)    return;
13         queue<TreeLinkNode *> q;
14         
15         root->next = NULL;
16         
17         q.push(root);
18         
19         while(!q.empty()){
20             TreeLinkNode *node = q.front();
21             q.pop();
22             
23             if(node->left != NULL && node->right != NULL){
24                 q.push(node->left);
25                 q.push(node->right);
26                 
27                 node->left->next = node->right;
28                 if(node->next == NULL)
29                     node->right->next = NULL;
30                 else{
31                     TreeLinkNode *node_next = q.front();
32                     node->right->next = node_next->left;
33                 }
34                 
35             }
36             
37         }
38         
39     }
40 };

 

相關文章