[leetcode] 117. 填充同一层的兄弟节点 II

117. 填充同一层的兄弟节点 II

116. 填充同一层的兄弟节点完全一样,二叉树的层次遍历。。这是这次不是完美二叉树了

class Solution {
    public void connect(TreeLinkNode root) {
        if (root == null) return;
        LinkedList<TreeLinkNode> queue = new LinkedList<>();
        queue.offer(root);

        TreeLinkNode flag = root;
        TreeLinkNode last = null;

        while (!queue.isEmpty()) {
            TreeLinkNode nowNode = queue.poll();

            if (last != null) {
                last.next = nowNode;
            }

            if (nowNode.left != null) queue.add(nowNode.left);
            if (nowNode.right != null) queue.add(nowNode.right);

            last = nowNode;

            if (flag == nowNode) {
                nowNode.next = null;
                flag = queue.peekLast();
                last = null;
            }
        }
    }
}
posted @ 2018-11-06 22:49  ACBingo  阅读(267)  评论(0编辑  收藏  举报