• Populating Next Right Pointers in Each Node


    题目链接

    Populating Next Right Pointers in Each Node - LeetCode

    注意点

    • 不要访问空结点
    • 二叉树是满二叉树也就是说如果有左节点一定会有右节点

    解法

    解法一:递归,DFS。因为是完美二叉树所以左子结点的next指针可以直接指向其右子节点,对于其右子节点的处理方法是,判断其父节点的next是否为空,若不为空,则指向其next指针指向的节点的左子结点,若为空则指向NULL。

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

    解法二:非递归。程序遍历每层的节点都按顺序加入queue中,而每当从queue中取出一个元素时,将其next指针指向queue中下一个节点即可。

    /*
    // Definition for a Node.
    class Node {
    public:
        int val;
        Node* left;
        Node* right;
        Node* next;
    
        Node() {}
    
        Node(int _val, Node* _left, Node* _right, Node* _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    };
    */
    class Solution {
    public:
        Node* connect(Node* root) {
            if(!root) return NULL;
            queue<Node*> q;
            q.push(root);
            while(!q.empty())
            {
                int size = q.size();
                for(int i = 0;i < size;i++)
                {
                    Node* temp = q.front();q.pop();
                    if(i != size-1) temp->next = q.front();
                    if(temp->left) q.push(temp->left);
                    if(temp->right) q.push(temp->right);
                }
            }
            return root;
        }
    };
    

    小结

    • 只要是遍历都有递归和非递归两种写法
  • 相关阅读:
    AOP Aspect 统一日志、异常处理、数据格式
    java基本成员默认值
    Jackson ObjectMapper
    logstash 安装 jdbc-output出错
    ElasticSearch定时删除数据(非时间结尾规律索引)
    docker安装部署
    K8s 使用helm 安装 EFK和ELK分布式日志分析系统系列(es版本:6.7.0;)
    JWT 验证
    JS查找数组中元素index
    oracle not in 失效
  • 原文地址:https://www.cnblogs.com/multhree/p/10632288.html
Copyright © 2020-2023  润新知