欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > 填充每个节点的下一个右侧节点Ⅱ-力扣

填充每个节点的下一个右侧节点Ⅱ-力扣

2025/5/11 15:40:15 来源:https://blog.csdn.net/why_12134/article/details/139496404  浏览:    关键词:填充每个节点的下一个右侧节点Ⅱ-力扣

本题如果使用BFS去层序遍历,代码和 填充每个节点的下一个右侧节点 题没有任何区别。但是使用已经建立好的next链表去做,则需要考虑到next指向的节点子节点是否为空的可能。

class Solution {
public:Node* connect(Node* root) {if(root == nullptr){return nullptr;}Node * head = root;while(head != nullptr){Node * dummy = new Node(0);Node * temp = dummy;for(Node* cur = head; cur != nullptr; cur = cur->next){if(cur->left != nullptr){temp->next =cur->left;temp = temp->next;}if(cur->right != nullptr){temp->next = cur->right;temp = temp->next;}}head = dummy->next;}return root;}
};

使用DFS来解决,通过一个数组来记录每一层的前节点,然后不断更新这个数组。

class Solution {
public:void dfs(Node* root, vector<Node*>& vec, int depth){if(root == nullptr){return;}if(depth >= vec.size()){vec.push_back(nullptr);}if(vec[depth] != nullptr){vec[depth]->next = root;}vec[depth] = root;dfs(root->left, vec, depth + 1);dfs(root->right, vec, depth + 1);}Node* connect(Node* root) {vector<Node*> vec;int depth = 0;dfs(root, vec, depth);return root;}
};

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词