Simple Java Solution!


  • -1
    S
    /**
     * Definition for binary tree with next pointer.
     * public class TreeLinkNode {
     *     int val;
     *     TreeLinkNode left, right, next;
     *     TreeLinkNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public void connect(TreeLinkNode root) {
            
            if(root==null)
                return;
            root.next = null;
            TreeLinkNode current=root;
            connectNodes(current);
        }
        
        public void connectNodes(TreeLinkNode current){
            
            if(current==null || (current.left==null && current.right==null))
                return;
    
            current.left.next=current.right;
            if(current.next!=null)
                current.right.next=current.next.left;
            else
                current.right.next=null;
            connectNodes(current.left);
            connectNodes(current.right);
    
        }
    }

Log in to reply
 

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