zoukankan      html  css  js  c++  java
  • LeetCode 116. 填充每个节点的下一个右侧节点指针

    题目描述

    给定一个完美二叉树,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:

    struct Node {
      int val;
      Node *left;
      Node *right;
      Node *next;
    }
    

    填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL
    初始状态下,所有 next 指针都被设置为 NULL

    示例:

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node

    思路解析

    层序遍历二叉树:

    1. 创建队列nodeQueue,并向队列中插入树的根节点root
    2. 若队列非空,则记录队列当前长度,并遍历当前队列,向队尾插入当前队列所有节点的左右子节点
    3. 按层序存入二维向量

    代码实现

    class Solution {
    public:
        Node* connect(Node* root) {
            std::queue<Node*> nodeQueue;
            vector<vector<Node*>> layerVec;
            if(root)
                nodeQueue.push(root);
            else
                return root;
            while(!nodeQueue.empty()) {
                vector<Node*> tmp;
                int length = nodeQueue.size();
                for(int i = 0; i < length; i++) {
                    if(nodeQueue.front()->left)
                        nodeQueue.push(nodeQueue.front()->left);
                    if(nodeQueue.front()->right)
                        nodeQueue.push(nodeQueue.front()->right);
                    tmp.push_back(nodeQueue.front());
                    nodeQueue.pop();
                }
                layerVec.push_back(tmp);
            }
            for(auto layer : layerVec) {
                for(int i = 0; i < layer.size() - 1; i++)
                    layer[i]->next = layer[i + 1];
                layer[layer.size() - 1]->next = NULL;
            }
            return root;
        }
    };
    
    /*
    // 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) {}
    };
    */
    
  • 相关阅读:
    sql执行顺序图
    solor5.4学习笔记
    linux 安装
    falsh,.swf文件修改z-index
    mysql 分区
    再次构架心得
    服务器,数据库连接注意mysql的user表
    数据库操作
    一知半见的load与get
    处理中文空格.replace((char)12288,' ')
  • 原文地址:https://www.cnblogs.com/xqmeng/p/13823771.html
Copyright © 2011-2022 走看看