[LeetCode] Populating Next Right Pointers in Each Node

public class Solution {
    public void connect(TreeLinkNode root) {
        if (root == null) {
            return;
        }
        Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeLinkNode right = null;
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeLinkNode node = queue.poll();
                node.next = right;
                right = node;
                if (node.right != null) {
                    queue.offer(node.right);
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
            }
        }
    }
}

 后来又做了一个O(1)空间复杂度的方法

public class Solution {
    public void connect(TreeLinkNode root) {
        if (root == null) {
            return;
        }
        TreeLinkNode pre = root;
        TreeLinkNode next = pre.left;
        while (next != null) {
            TreeLinkNode tmp = pre.left;
            while (pre != null) {
                if (tmp == pre.left) {
                    tmp.next = pre.right;
                    tmp = tmp.next;
                    pre = pre.next;
                } else {
                    tmp.next = pre.left;
                    tmp = tmp.next;
                }
            }
            pre = next;
            next = pre.left;
        }
    }
}

 

posted @ 2015-12-01 03:18  Weizheng_Love_Coding  阅读(131)  评论(0编辑  收藏  举报