time O(n) ,sapce O(n)
/* // 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; } }; */ /** 层序遍历,然后每一层左边节点指向右边节点,最后一个节点指向NULL **/ class Solution { public: Node* connect(Node* root) { if(root==NULL||root->left==NULL) return root; queue<Node*>q; q.push(root->left),q.push(root->right); while(!q.empty()){ int k=q.size(); Node* l,*r=q.front(); q.pop(); if(r->left) q.push(r->left),q.push(r->right); for(int i=1;i<k;i++){ l=r,r=q.front();q.pop(); l->next=r; if(r->left) q.push(r->left),q.push(r->right); } } return root; } };
原文地址:https://www.cnblogs.com/joelwang/p/10920448.html
时间: 2024-10-10 21:15:55