题目
Given a binary tree
struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; }
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?
承接上一题,http://blog.csdn.net/xift810/article/details/20537657 把二叉树的next补完,但是不是完美二叉树了。
1 关键点是旁边的概念不能用root.next.left来得出了。
2 旁边现在的意思是,右边节点中,出现第一个孩子节点的情况。
3 我一开始的代码分了很多类,算是硬写的;基本就等于我脑中的思路。AC了。
public class Solution {
public void connect(TreeLinkNode root) {
if(root==null){
return ;
}
if(root.next==null){
if(root.right!=null){
root.right.next=null;
}
if(root.left!=null){
root.left.next=root.right;
}
}
else{
if(root.right!=null){
TreeLinkNode temp = root;
while(temp.next!=null){
temp = temp.next;
if(temp.left!=null){
root.right.next = temp.left;
break;
}
if(temp.right!=null){
root.right.next = temp.right;
break;
}
}
if(root.left!=null){
root.left.next = root.right;
}
}
else{
if(root.left!=null){
TreeLinkNode temp = root;
while(temp.next!=null){
temp = temp.next;
if(temp.left!=null){
root.left.next = temp.left;
break;
}
if(temp.right!=null){
root.left.next = temp.right;
break;
}
}
}
}
}
connect(root.right);
connect(root.left);
}
}
4 但是,这样很不好,后续如果回头看,根本看不懂写的是什么。
5 所以总结了下,重写。预先找到旁边孩子的结点,之后再分情况讨论,这样子,会好很多。突然想到了乘法合并率,嘿嘿。
public class Solution {
public void connect(TreeLinkNode root) {
if(root==null){
return ;
}
TreeLinkNode rnext = root.next;
TreeLinkNode record = null;
while(rnext!=null){
if(rnext.left!=null){
record = rnext.left;
break;
}
if(rnext.right!=null){
record = rnext.right;
break;
}
rnext= rnext.next;
}
if(root.right!=null){
root.right.next=record;
}
if(root.left!=null){
if(root.right != null){
root.left.next = root.right;
}else{
root.left.next = record;
}
}
connect(root.right);
connect(root.left);
}
}