Populating Next Right Pointers in Each Node
Given a binary tree
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set toNULL
.
Initially, all next pointers are set toNULL
.
Note:
You may only use constant extra space.
Recursive approach is fine, implicit stack space does not count as extra space for this problem.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
Example
Given the following perfect binary tree,
After calling your function, the tree should look like:
Note
主要是一层一层遍历去连结,有两种情况:
左右孩子相连
右孩子连左孩子
通过next指针可以单层从左到右走,给的是perfect树
需要注意的是需要判断一下curr的left和right是不是空,corner case是只有一个root
递归和迭代类似
Code
Last updated