2016年2月1日 星期一

LEET code -- Populating Next Right Pointers in Each Node

 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



Subscribe to see which companies asked this question

只要分別去走(LL->left, LL->right) (LL->right, RR->left) (RR->left, RR->right)
就可以了  且next預設是NULL




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  struct TreeLinkNode *left, *right, *next;
 * };
 *
 */
void connect(struct TreeLinkNode *root) {
    if(root==NULL)return;
    //if(root->right!=NULL)root->right->next=NULL;
    root->next=NULL;
    parse(root->left,root->right);
}

void parse(struct TreeLinkNode *LL,struct TreeLinkNode *RR ){
    if(LL==NULL || LL->next!=NULL)return;
    //if(RR->right!=NULL)RR->right->next=NULL;
    LL->next=RR;
    
    parse(LL->left,LL->right);
    parse(LL->right,RR->left);
    parse(RR->left,RR->right);
}
-------------------
更好的解法:
事實上就是DFS



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  struct TreeLinkNode *left, *right, *next;
 * };
 *
 */
void connect(struct TreeLinkNode *root) {
    if(root==NULL)return;
    //if(root->right!=NULL)root->right->next=NULL;
    
    parse(root);
}

void parse(struct TreeLinkNode *rt){
    if(rt->left==NULL)return;
    //if(RR->right!=NULL)RR->right->next=NULL;
    rt->left->next=rt->right;
    rt->right->next = rt->next==NULL? NULL:rt->next->left;
    parse(rt->left);
    parse(rt->right);
}

沒有留言:

張貼留言