题目:
节点中多了一个next引用指向该节点的右边节点,若没有右边节点则next=null,且只能使用O(1)辅助空间。
struct TreeLinkNode{
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
例如:
Given the following perfect binary tree,
1
/ \
2 3
/ \ / \
4 5 6 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL
思路:层序遍历二叉树,并操纵next引用赋值.
代码如下:
/** * Definition for binary tree with next pointer. * public class TreeLinkNode { * int val; * TreeLinkNode left, right, next; * TreeLinkNode(int x) { val = x; } * } */ import java.util.*; public class Solution { public void connect(TreeLinkNode root) { if(root == null) return; LinkedList<TreeLinkNode> list=new LinkedList(); list.add(root); int cur=1;//list中存储的二叉树当前层节点数; int next=0;//list中存储的二叉树下一层节点数; while(list.size()!=0) { TreeLinkNode node=list.remove(0); cur--; if(cur!=0)//若node右边有节点,next指向右边节点; { node.next=list.get(0); }else//若node右边无节点,next指向null; { node.next=null; } if(node.left!=null) { list.add(node.left); next++; } if(node.right!=null) { list.add(node.right); next++; } if(cur == 0)//当前层遍历结束,遍历下一层; { cur=next; next=0; } } } }
节点中多了一个next引用指向该节点的右边节点,若没有右边节点则next=null.