题目:
给定一个二叉树
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL
。
初始状态下,所有 next 指针都被设置为 NULL
。
说明:
- 你只能使用额外常数空间。
- 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
示例:
给定二叉树,
1
/ \
2 3
/ \ \
4 5 7
调用你的函数后,该二叉树变为:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL
第一种办法,时间长
package test;
import java.util.ArrayList;
import java.util.List;
class TreeLinkNode
{
int val;
TreeLinkNode left, right, next;
TreeLinkNode(int x)
{
val = x;
}
}
public class LC116Try1
{
public void connect(TreeLinkNode root)
{
List<TreeLinkNode> list = new ArrayList<TreeLinkNode>();
getPass(root, 0, list);
}
public void getPass(TreeLinkNode root, int level, List<TreeLinkNode> list)
{
if (root == null)
{
return;
}
if (list.size()>=level+1)
{
list.get(level).next = root;
list.set(level, root);
}
else
{
list.add(root);
}
getPass(root.left, level + 1, list);
getPass(root.right, level + 1, list);
}
}
第二种解决办法:时间还可以
package test;
public class LC116Try2
{
public void connect(TreeLinkNode root)
{
if (root == null)
{
return;
}
TreeLinkNode node = new TreeLinkNode(-1);
TreeLinkNode cur = root;
for (TreeLinkNode pre = node; cur != null;cur=cur.next)
{
if(cur.left!=null){
pre.next=cur.left;
pre=pre.next;
}
if(cur.right!=null){
pre.next=cur.right;
pre=pre.next;
}
}
connect(node.next);
}
}
第三种解决办法:貌似时间是最短的
//层次遍历, O(n)空间
// 递归
public class Solution {
public void connect(TreeLinkNode root){
if(root == null) return;
if(root.left != null){
root.left.next = root.right;
if(root.next != null){
root.right.next = root.next.left;
}
}
connect(root.left);
connect(root.right);
}
}
非递归算法:层次遍历
public Node connect(Node root) {
if(root==null){
return root;
}
Deque<Node> stack= new LinkedList<>();
stack.push(root);
Node p=root;
Node t=null;
while(stack.size()>0){
int size= stack.size();
for(int i=0;i<size;i++){
p=stack.pollLast();
if(p.left!=null){
stack.push(p.left);
}
if(p.right!=null){
stack.push(p.right);
}
if(i==0){
t=p;
continue;
}
t.next=p;
t=p;
}
t=null;
}
return root;
}
哈哈