zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    centos6.5的开机自动部署出现unsupported hardware detected
    Nginx的安装
    sshpass的使用方法
    dhcp 的安装和配置文件
    SMBus总线概述
    SMBus与I2C的差别
    vim搭建笔记
    pcie dma的玩法
    Virtex6 PCIe 超简版基础概念学习(二)
    揭开Altera公司支持OpenCL的设计工具的神秘面纱
  • 原文地址:https://www.cnblogs.com/JasonPeng1/p/12105476.html
Copyright © 2011-2022 走看看