Q117. Populating Next Right Pointers in Each Node II
Last updated
Was this helpful?
Last updated
Was this helpful?
直达:
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,
After calling your function, the tree should look like:
对于任意一棵树来说,可以分成下面三种情况
若左子树存在,右子树也存在,左子树的next是右子树,右子树的next是父节点的兄弟节点的第一个孩子(root的大侄子);
若左子树存在,右子树不存在,左子树的next是父节点的兄弟节点的第一个孩子;
若左子树不存在,右子树存在,右子树的next是父节点的兄弟节点的第一个孩子;
所以问题的关键是寻找root的大侄子,依次查看root->next是否存在左右子树,否则,root = root->next;
同样,可以通过递归操作完成。