2018年2月9日 星期五

[116] Populating Next Right Pointers in Each Node

感動!!!
我覺得我的pointer真的有進步!!! Orz

一般的binary tree, 除了left & right child之外,
左小孩指到右小孩, 右小孩指到parent的sibling的左小孩
(妳還是說中文吧)
沒想到很快就寫完了我真的要哭了(奔入雨中)(這樣也要奔入雨中XD?!)

Populating Next Right Pointers in Each Node
/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  struct TreeLinkNode *left, *right, *next;
 * };
 *
 */
void connect_recursive(struct TreeLinkNode *ptr) {

    if (ptr->left == NULL)
        return;
    ptr->left->next = ptr->right;
    if (ptr->next != NULL)
        ptr->right->next = ptr->next->left;
    else
        ptr->right->next = NULL;
    connect_recursive(ptr->left);
    connect_recursive(ptr->right);

}
void connect(struct TreeLinkNode *root) {
    if (root == NULL)
        return;
    root->next = NULL;
    if(root->left ==NULL)
        return;

    root->left->next = root->right;
    root->right->next = NULL;
    connect_recursive(root->left);
    connect_recursive(root->right);  
}
雖然別人寫起來好像更美呢哈哈哈哈哈
算了Orz
就是說先一層一層走完, 左到右, (因為有next, 所以可以直接往右)
走完一層再給它的left 往下一層走
用兩個 while 完成.


20230725更新
重寫一次,recursive 變漂亮了呢。這也算是一種進步吧XD

/**
* Definition for a Node.
* struct Node {
* int val;
* struct Node *left;
* struct Node *right;
* struct Node *next;
* };
*/

struct Node* connect(struct Node* root) {
if (root==NULL)
return NULL;
if (root->left==NULL)
return root;
root->left->next=root->right;
if (root->next !=NULL)
root->right->next=root->next->left;
connect(root->left);
connect(root->right);
return root;
}

沒有留言:

張貼留言