文章目录
题目描述
思路 && 代码
- 主要思路:先右,再左(因为左边依赖右边!)
- getNext():当前节点,无法包办子节点的 next 了,这份责任交给当前节点的 next !当然,如果 next 不行,那么继续递归传递责任(有点像责任链模式)
- 对了,不一定得层序 BFS,因为对于当前节点来说,只要右边已经维护了就行。
- 其他见注释~已经拉满注释了~
class Solution {public Node connect(Node root
) {if(root
== null) return root
;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;}
}
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)的全部内容,希望文章能够帮你解决所遇到的问题。
如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。