5-line 1ms java iterative solution O(n) time O(1) space


  • 8
    M
    public class Solution {
        public void connect(TreeLinkNode root) {
            if (root == null) { return; }
            for (TreeLinkNode head=root; head.left!=null; head=head.left) {
                for (TreeLinkNode parent=head; parent!=null; parent=parent.next) {
                    parent.left.next = parent.right;
                    if (parent.next != null) { parent.right.next = parent.next.left; }
                }
            }
        }
    }

  • 0
    V

    Beautiful !! Thanks for Sharing


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.