• 116.填充每个节点的下一个右侧节点指针(DFS 递归+ BFS 迭代 )


    2019-12-27

    08:52:23

    解法1:DFS 递归解决

    /*
    // Definition for a Node.
    class Node {
    public:
        int val;
        Node* left;
        Node* right;
        Node* next;
    
        Node() : val(0), left(NULL), right(NULL), next(NULL) {}
    
        Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
    
        Node(int _val, Node* _left, Node* _right, Node* _next)
            : val(_val), left(_left), right(_right), next(_next) {}
    };
    */
    class Solution {
    public:
        int flag = 1;
        Node* connect(Node* root) {
            if(!root) return NULL;
            if(flag){
                root->next = NULL;
                flag = 0;
            }
            if(!(root->left)){
                return root;
            }
            else root->left->next = root->right;
            if(root->next){
                root->right->next = root->next->left;
            }else{
                root->right->next = nullptr;
            }
            connect(root->left);
            connect(root->right);
            return root;
        }
    };
     

    解法2: BFS 迭代

    /*
    // Definition for a Node.
    class Node {
    public:
        int val;
        Node* left;
        Node* right;
        Node* next;
    
        Node() : val(0), left(NULL), right(NULL), next(NULL) {}
    
        Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
    
        Node(int _val, Node* _left, Node* _right, Node* _next)
            : val(_val), left(_left), right(_right), next(_next) {}
    };
    */
    class Solution {
    public:
        Node* connect(Node* root) {
            Node *now = root;
            while(now != NULL){
                Node *temp = now;
                while(temp!=NULL){
                    if(temp->left != NULL){
                        temp->left->next = temp->right;
                    }
                    if(temp->right != NULL && temp->next != NULL){
                        temp->right->next = temp->next->left;
                    }
                    temp = temp->next;
                }
                now = now->left;
            }
            return root;
        }
    };
  • 相关阅读:
    Activator.CreateInstance 反射实例化对象
    MVC Form提交
    Redis 下载
    List<T> 序列化与反序列化
    快速反射DataTable
    数据库特性
    javascript判断文件大小
    MD5
    HttpHelper
    cacheHelper
  • 原文地址:https://www.cnblogs.com/JasonPeng1/p/12105476.html
Copyright © 2020-2023  润新知