Populating Next Right Pointers in Each Node II 题解

题目来源:Populating Next Right Pointers in Each Node II

>

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.
For example,
Given the following binary tree,
         1
       /  \
      2    3
     / \    \
    4   5    7
After calling your function, the tree should look like:
         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \    \
    4-> 5 -> 7 -> NULL

解题思路:

Populating Next Right Pointers in Each Node思路一致,值得注意的是

  • 在填充下一层next时,当前层的next要找完。//Attention 0

  • 往下走时,可能前面的节点没有孩纸节点,也要找完同一层的节点是否存在孩纸节点。//Attention 1

上面代码确实比较丑陋~ 其实着眼于同一层之前通过pre来记录同一层的前一个节点的话,代码就好看得多。 leetcode-cpp

Last updated

Was this helpful?