每日一题 2019 - 04 - 29
题目:
Given a binary tree
1 | struct Node { |
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL
.
Initially, all next pointers are set to NULL
.
Example:
1 | Input: {"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":null,"right":null,"val":4},"next":null,"right":{"$id":"4","left":null,"next":null,"right":null,"val":5},"val":2},"next":null,"right":{"$id":"5","left":null,"next":null,"right":{"$id":"6","left":null,"next":null,"right":null,"val":7},"val":3},"val":1} |
Note:
- You may only use constant extra space.
- Recursive approach is fine, implicit stack space does not count as extra space for this problem.
解法:
这个题是 leetcode 116
的改进版,也即这个二叉树并不是一颗满二叉树,所以需要考虑的问题更多,比如:
- 一个结点缺少左子节点
- 一个结点缺少右子节点
- 一个结点同时缺少左右节点
所以这个题就不能单纯的深度遍历所有层的左子节点,所以可以更换思路为使用一个临时变量 tmp
记录当前根节点的下一个节点,通过判断下一个节点是否存在左右子节点来供当前节点连接;
同时由于要遍历到二叉树的最下层,且存在着左右子节点一方或者两方都缺失的情况,所以需要对每一层进行遍历,找到不缺失左右子节点的结点往下层遍历;
还需要注意一个地方,待连接的结点往后连接的过程要先判断右节点是否为空,因为右节点已经存在的情况下,左节点已经连接到右节点上,如果右节点不存在,那么把左节点往下继续连接;
代码:
1 | /* |