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
分类:二叉树
题意:对于每个节点,将next指向其右边的相邻节点,如果右边没有节点,则指向Null。该树为任意二叉树。
解法1:层次遍历。使用两个栈来交替记录两层。对于每个层,逐一连接即可。
解法2:层次遍历,和Populating Next Right Pointers in Each Node里面的解法类似,主要问题是,1,找到下一层开始的第一个节点;2,找到当前节点右边的第一个节点
解法3:层次遍历。关键在于保留下一层的第一个节点。另外保留一个pre指向前一个节点。
解法4:将解法3的迭代换成递归
原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/46593639