赞
踩
package Tree; import java.util.LinkedList; import java.util.Queue; public class Connect_117 { class Node { public int val; public Node left; public Node right; public Node next; public Node() { } public Node(int _val) { val = _val; } public Node(int _val, Node _left, Node _right, Node _next) { val = _val; left = _left; right = _right; next = _next; } } public Node connect(Node root) { if(root==null) { return root; } // 每一行的节点用队列存储起来 Queue<Node> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { Node pre = null; int size=queue.size(); for (int i = 0; i < size; i++) { // 每一行串起来 Node cur = queue.poll(); if (i > 0) { pre.next = cur; } pre = cur; // 下一行存入队列 if (cur.left != null) { queue.offer(cur.left); } if (cur.right != null) { queue.offer(cur.right); } } } return root; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。