欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

【LeetCode笔记】117.填充每个节点的下一个右侧节点指针 II(二叉树、DFS)

发布时间:2024/7/23 编程问答 41 豆豆
生活随笔 收集整理的这篇文章主要介绍了 【LeetCode笔记】117.填充每个节点的下一个右侧节点指针 II(二叉树、DFS) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

文章目录

  • 题目描述
  • 思路 && 代码

题目描述

  • 很烦…面试被这题干碎了,赶紧给查漏补缺一波!

思路 && 代码

  • 主要思路:先右,再左(因为左边依赖右边!)
  • getNext():当前节点,无法包办子节点的 next 了,这份责任交给当前节点的 next !当然,如果 next 不行,那么继续递归传递责任(有点像责任链模式)
  • 对了,不一定得层序 BFS,因为对于当前节点来说,只要右边已经维护了就行。
  • 其他见注释~已经拉满注释了~
/* // Definition for a Node. class Node {public int val;public Node left;public Node right;public Node next;public Node() {}public Node(int _val) {val = _val;}public Node(int _val, Node _left, Node _right, Node _next) {val = _val;left = _left;right = _right;next = _next;} }; */class Solution {// 总思路:在当前层已经完善 next 的情况下,用当前层信息,对下一层进行维护public Node connect(Node root) {// Case 1:空节点if(root == null) return root;// Case 2:左右双全:直接左指右if(root.left != null && root.right != null) {root.left.next = root.right;}// Case 3: 有左无右:靠你了,我的下一个节点!if(root.left != null && root.right == null) {root.left.next = getNext(root.next); // 传入 root 的 next,用以获取可行的 next}// Case 4: 有右if(root.right != null) {root.right.next = getNext(root.next); // 同 Case 3}// 先右再左:因为得先获得右边节点的 nextconnect(root.right);connect(root.left);return root;}// 获取第一个节点。Node getNext(Node root) {// Case 1:为空:直接返回 nullif(root == null) return null; // Case 2:有左:返左节点if(root.left != null) return root.left;// Case 3:有右:返右节点if(root.right != null) return root.right;// Case 4:左右都没有,但是有下一个节点:继续递归查找if(root.next != null) return getNext(root.next);// Case 5:摆烂,啥都没有:那就只能 null 了。return null;} }
  • 无注释版,其实就 16 行解决!
class Solution {public Node connect(Node root) {if(root == null) return null;if(root.left != null && root.right != null) {root.left.next = root.right;}if(root.left != null && root.right == null) {root.left.next = getNext(root.next);}if(root.right != null) {root.right.next = getNext(root.next);}connect(root.right);connect(root.left);return root;}Node getNext(Node root) {if(root == null) return null;if(root.left != null) return root.left;if(root.right != null) return root.right;if(root.next != null) return getNext(root.next);return null;} }

总结

以上是生活随笔为你收集整理的【LeetCode笔记】117.填充每个节点的下一个右侧节点指针 II(二叉树、DFS)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。