题目原文:
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节点。
题目分析:
与Middle-题目17类似,区别是这里面的二叉树是普通二叉树,上一题则是完全二叉树。所以左孩子的next不一定是右孩子,右孩子的next也不一定是父节点next的左孩子,而是从父节点开始,一直向右找到一个有孩子的同层节点,然后指向其孩子(如果有左孩子就是左孩子,没有就是右孩子)。
所以每排完一层之后向下深搜的时候,要先搜右子树,再搜左子树,故本题要用逆前序遍历!!!,如果是常规的前序遍历,向左子树深搜的时候由于右子树没处理,会有一些next没连上。
源码:(language:java)
public class Solution {
public void connect(TreeLinkNode root) {
if(root!=null)
dfs(root,root.left,root.right);
}
private void dfs(TreeLinkNode parent, TreeLinkNode leftchild, TreeLinkNode rightchild) { // asserted that parent isn't null
TreeLinkNode p = parent;
while (p.next!=null && (p==parent || (p.left==null&&p.right==null)))
p=p.next;
if(leftchild!=null) {
if(rightchild!=null)
leftchild.next = rightchild;
else {
if(p!=parent)
leftchild.next = p.left!=null?p.left:p.right;
}
}
if(rightchild!=null) {
if(p!=parent)
rightchild.next = p.left!=null?p.left:p.right;
}
if(rightchild!=null)
dfs(rightchild, rightchild.left, rightchild.right);
if(leftchild!=null)
dfs(leftchild, leftchild.left, leftchild.right);
}
}
成绩:
2ms,beats 32.02%,众数2ms,39.09%
Cmershen的碎碎念:
Follow up有说到,要常数的空间复杂度,不知道递归是不是不合要求的?如果不合要求,那么可以通过改造前序遍历来实现,貌似会很麻烦……