Populating Next Right Pointers in Each Node II
https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/description/
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
You may only use constant extra space.
Thoughts
对二叉树每个结点增加next指针指向每层下一个结点。不难想到按层遍历,对每个结点,假设它所在的层已经连好了,通过它去连接下一层的结点。用pre_c记录上一个被连的结点,用它去连当前结点的子结点,再更新pre_c。当前结点处理好后,直接利用它的next就蹦到本层下一个结点。当next为null时说明本层已经遍历完,下层都已连好,需要一个额外指针next_lev记录下层第一个结点。
Code
Analysis
Errors:
node = node.next忘了写。
做题耗时11min
时间复杂度O(n), 空间复杂度O(1).
Last updated
Was this helpful?